-3

I am trying to write JavaScript that has a banner. When I mouse over the banner it changes into a different banner. Then when I mouse out it should stay the same. Then when I mouse back over it should go back to the original banner. However I can't figure out how to do this. Any advice?;

Dolbyover
  • 89
  • 1
  • 2
  • 10

2 Answers2

2

use Javascript

<img onmouseover="changeImage()" id="myBanner" src="Images\image1.jpg"/>
<script>
 function changeImage(){
  if(document.getElementById("myBanner").src=="Images\image1.jpg"){
   document.getElementById("myBanner").src="Images\image2.jpg"
  }else{
   document.getElementById("myBanner").src="Images\image1.jpg"
  }
 }
</script>

This works for 2 images toggling between each other. If you want to use more, I suggest using a variable that you pass to the function and a switch that goes through all your options.

David Starkey
  • 1,840
  • 3
  • 32
  • 48
0

You only need a single mouseover to handle the toggle:

(function() {
    var imgTag = document.getElementsByTagName('img')[0];
    imgTag.addEventListener('mouseover', function(e) {
        var currentImage = imgTag.getAttribute('src');

        imgTag.setAttribute('src', imgTag.getAttribute('data-other-image'));
        imgTag.setAttribute('data-other-image', currentImage);
    });
}());

Demo: http://jsfiddle.net/EsNEC/

This way you don't have inline javascript in your HTML.

PeeHaa
  • 71,436
  • 58
  • 190
  • 262