Learning JavaScript Functions - 2

Sponsored Links

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>

Check the result here: Welcome

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 this 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.

Background Color 1
Background Color 2
Background Color 3
Background Color 4
Background Color 5
Background Color 6
Background Color 7
Background Color 8
Background Color 9
Original Color

Assignments

  1. Create a function that loads a new window 300 X 200 pixels in dimensions.
  2. Now change the code above so that you can pass the URL as argument to the function

Click here for possible answers



Click this button if you liked the article!
AddThis Social Bookmark Button

Page contents:

JavaScript Tutorial


Please vote