WDN Logo

home-icon Home / JavaScript / JavaScript – Image Change Using Functions

JavaScript – Image Change Using Functions

JavaScript - Image Change Using Functions

The main use of function is to prevent us from writing the same code again and again because we can call the same function with a different set of parameters.

In the image roll-over script of the previous session, the code for changing the image was placed inside the event handlers. This is fine if there are one or two images. In case of several images, it is advisable to pack the code in a function that can be called repeatedly by event handlers using different parameters.

There are two important things in an image roll-over code. One is the image name and the other is the image source. Thus, we have to construct a function that accepts these two arguments and changes the image source.

function roll_over(img_name, img_src)
   document[img_name].src = img_src;

We can now call this function from our even handlers and pass it the two arguments.

<A HREF="some.html" onmouseover="roll_over('but1', 'icon2.gif')"
onmouseout="roll_over('but1', 'icon1.gif')">
<IMG SRC="icon1.gif" WIDTH="100" HEIGHT="50"
NAME="but1" BORDER="0">

On Mouse Over

Sponsored Links


Your comments
Star icon IMPORTANT Have a question / problem? Click here to ask an expert.

Caps Lock jokes and funny images

Sponsored Links


How do I view a deleted web page?
Is there a way to view a deleted web page - one that is no longer available? Yes there is and the solution is quite simple. [more...]


Gmail ran for more than 5 years with the beta tag. It was removed on the 7th of July 2009.Google had launched their free email service on 1st April 2004 with 1 GB storage space. This was 20 times more than what was being offered by the competition at that time. [more...]

Share on Whats app Share on Facebook Share on Twitter Share on Google plus