Categories:
Partners

Example- Making use of the "data" attribute of HTML 5 in image rollovers

Custom attributes provide an intuitive way to store settings for an element that's then parsed by JavaScript. A classic example is the JavaScript rollover effect where there needs to be a place to define the paths to the images for the over and out states. The "data" attribute lends itself well as such a place.

The following script looks for all images on the page with the "data-over" and ""data-out" attributes, which are used to store the image paths for the image's over and out states. If these attributes are found, the script preloads the over image, then assigns a rollover effect to the target image:

Demo:

The code:

<a href="http://www.javascriptkit.com"><img src="default.jpg" data-out="default.jpg" data-over="over.jpg" /></a>
<a href="http://www.javascriptkit.com"><img src="default.jpg" data-out="default.jpg" data-over="over.jpg" /></a>
<a href="http://www.javascriptkit.com"><img src="default.jpg" data-out="default.jpg" data-over="over.jpg" /></a>

<script type="text/javascript">

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
}

//Following function should be called at the end of the page:
imagerollover()

</script>

By defining the image paths directly inside the image, they are readily accessible and easy to update. Previously this information either had to be defined inside your script, which makes it harder to modify, or perhaps inside the "rel" and "rev" attributes of the image's parent A element, which isn't exactly what these attributes were intended for. Now you have another arguably better option, one that W3C endorses exactly for this purpose too!

Copyright 1997-2014 JavaScript Kit. NO PART may be reproduced without author's permission.