السبت، 14 أبريل 2012

Image rollover script

Image rollover script

Step 1:Add the following code to the HEAD section of your page.

function imagerollover(){
 var allimages=document.getElementsByTagName("img")
 var preloadimages=[]
 for (var i=0; i<allimages.length; i++){
  if (allimages[i].getAttribute("data-over")){ //if image carries "data-over" attribute
   preloadimages.push(new Image()) //preload "over" image
   preloadimages[preloadimages.length-1].src=allimages[i].getAttribute("data-over")
   allimages[i].onmouseover=function(){
    this.src=this.getAttribute("data-over")
   }
   allimages[i].onmouseout=function(){
    this.src=this.getAttribute("data-out")
   }
  } //end if
 } //end for loop
}

//Usage: Call following function at the end of the page:
//imagerollover()
 
 
 
Step 2: Then, to give any image on the page a rollover effect, insert inside its tag the "data-over" and "data-out" attributes that's set to the image paths of the over and out (default) images. For example:
<img src="default.jpg" data-over="out.jpg" data-out="default.jpg" />
or:
<a href="http://www.javascriptkit.com"><img src="http://mysite.com/off.gif" data-over="http://mysite.com/on.gif" data-out="http://mysite.com/off.gif" /></a>
Last but not least, you must call the following code snippet at the very end of your page (ie: right above the <body> tag)  to activate the effect:
<script type="text/javascript">
//Following function should be called at the end of the page:
imagerollover()
</script>

HTML Validation

The above script takes advantage of HTML 5's "data" attribute. For pages that use this script, if you wish it to validate, you should insert at the very top of your page the recommended HTML 5 doctype, which is:
<!DOCTYPE HTML>
 

ليست هناك تعليقات:

إرسال تعليق