vic
vic

Reputation: 1

How to add image rollover to Javascript

I have an image that when clicked hidden content is shown and it switches to a different image, and when clicked again it reverts to its normal state. I'm using a bit of code I found on this site and it works great. I would like to add a rollover to the image as well. Im stumped on how to do this, as I am not very well versed in javascript. Any help is appreciated.

<head>
<script language="javascript" type="text/javascript">
var imageNo = 2;
function swapImage() {
image = document.getElementById('image')
switch (imageNo) {
 case 1:
   image.src = "images/img.png"
   imageNo = 2
   document.getElementById('content').style.display = 'none'
   return(false);
case 2:
   image.src = "images/img1.png"
   imageNo = 1
    document.getElementById('content').style.display = 'block'
    return(false);
}
}
</script>
 </head>

 <body>
  <h4><a href="#"><img id="image" name="image" src="images/img.png" border="0" onclick="swapImage();"/></a></h4>
  <div id="content" style="display:none">This content toggles</span>
 </body><code>

Upvotes: 0

Views: 325

Answers (3)

Red Forks
Red Forks

Reputation: 1

The CSS :hover selector is simple:

#image:hover {
    background: url(your/image.png);
}

Upvotes: 0

marspzb
marspzb

Reputation: 364

Please see the following fiddle http://jsfiddle.net/AGgha/3/.
It uses jQuery ( http://jquery.com/),which makes your js dev much easier and lets you animate your divs.
It uses the setInterval for infinte swaping as you're on the img. I've also added some improvements of your code for making it a bit better use it if you want.

Upvotes: 1

ShankarSangoli
ShankarSangoli

Reputation: 69905

Use onmouseover event if you want the same behavior on mouse over of the image element.

<img id="image" name="image" src="images/img.png" border="0" 
       onclick="swapImage();" onmouseover="swapImage();"/>

Upvotes: 0

Related Questions