Learning JavaScript Functions – 2

Learning JavaScript Functions – 2 cover image
  1. Home
  2. JavaScript
  3. Learning JavaScript Functions – 2

Here is how you solve the problem of using the same function to open windows with different urls.
Take a good look at the code below:

function open_win(url_add)
   {
   window.open(url_add,'welcome',
   'width=300,height=200,menubar=yes,status=yes,
   location=yes,toolbar=yes,scrollbars=yes');
   }

The function has a parameter url_add inside the parenthesis. It occurs in the function once again at the place where we specify the URL for the new window, however, this time it’s not enclosed in quotes.
To call the open_win function, we pass an argument which is the url address of the document we plan to display in the new window.

open_win("welcome.html");

When open_win is called, we pass the url as an argument. Note that the url is a string data type and has to be enclosed in quotes.
The function picks up the argument and puts it in the value of the url_add variable. The variable containing a URL address (welcome.html) and is used inside the function in place of the actual URL string.

<A HREF="javascript:void(0)" 
onclick="open_win('welcome.html')">Welcome message</A>

Click to view the result

So if we want to open 10 pop-up windows each displaying a different URL, we call the function 10 times, each time using with a different URL as argument. The beauty is that we don’t have to write separate functions for displaying pop-up windows with individual URL addresses; the same function is sufficient.

Spicing up a page

I’ve placed this function in the HTML head.

function change_back(colorval)
   {
   document.bgColor=colorval;
   }

I can then call it from several event handler code, as

<A HREF="javascript:void(0)"
onmouseover="change_back('#CCCC99')">
Background Color 1</A>

Each link below, passes a different color code to the function. Move your mouse over the links below to see the effect.

Click to view the result

JavaScript