Javascript image mouse rollover

Javascript image mouse rollover cover image
  1. Home
  2. JavaScript
  3. Javascript image mouse rollover

Let’s consider you have 10 images being used as icons on a web page and since you have read the previous article, you plan to have JavaScript image rollovers for each image. Writing JavaScript code inside the <a> for each image becomes very messy, not to mention, very troublesome and error prone.

A simple solution would be to collect the code into a function that can be placed between <script> tags, inside the HTML head or in an external JavaScript (.js) file. We can then call this function with appropriate arguments from the event handlers.

<script type="text/javascript">
<!--

function roll(img_name, img_src)
   {
   document[img_name].src = img_src;
   }

//-->
</script>

This function expects two arguments, one is the image name and the other is the image source. The function is called from onmouseover and onmouseout event handlers and the two parameters are passed to it.

<a href="somewhere.html" 
onmouseover="roll('sub_but', 'movedown.gif')" 
onmouseout="roll('sub_but', 'movetup.gif')">

<img src="moveup.gif" width="143" height="39" border="0" 
alt="Move your mouse over me" name="sub_but" />

</a>

Click here to see how this works!

Building upon what we learnt here, let’s see how we can change two images simultaneously.

JavaScript