Change image with JavaScript (or jQuery)

abstract

One of the most asked questions by JavaScript beginners is how to change image on the html page when mouse pointer enters the image or maybe some other object on the page. This is called mouseover. Here is a little tutorial that covers most of the relevant cases.

compatible

All modern browsers

Let us start with an example page where an img tag is located:

<html><head><script type="text/javascript">

functionshowHover(img){if(img){img.src='/i/ex_hover.gif';}}functionshowNormal(img){if(img){img.src='/i/ex.gif';}}functioninit(){/* here we will place our code */varex1=document.getElementById('ex1');if(ex1.addEventListener){//trying the standard wayex1.addEventListener('mouseover',function(){showHover(ex1);},false);ex1.addEventListener('mouseout',function(){showNormal(ex1);},false);}else{//in case it's an InternetExplorerex1.attachEvent('mouseover',function(){showHover(ex1);});ex1.attachEvent('mouseout',function(){showNormal(ex1);});}varex2=document.getElementById('ex2');varhlink=document.getElementById('hlink');if(hlink.addEventListener){hlink.addEventListener('mouseover',function(){showHover(ex2);},false);hlink.addEventListener('mouseout',function(){showNormal(ex2);},false);}else{hlink.attachEvent('mouseover',function(){showHover(ex2);});hlink.attachEvent('mouseout',function(){showNormal(ex2);});}}window.onload=init;

</script></head><body><h1>Example1</h1><br/><imgid='ex1'src="/i/ex.gif"/><hr/><h1>Example2</h1><br/><imgid='ex2'src="/i/ex.gif"/><ahref="#"id="hlink">hover this link</a></body></html>

That's a lot of code! :) All that dancing around IE, long method names...