Posted By

skatan on 09/13/07


Tagged

javascript


Versions (?)

Who likes this?

4 people have marked this snippet as a favorite

jonhenshaw
basicmagic
vali29
imaginethepoet


unobtrusive mouseover image swap with preloader


 / Published in: JavaScript
 

Needs object detection to be completely unobtrusive

  1. function imageSwap(id) {
  2. var links = document.getElementById(id).getElementsByTagName("a");
  3. var imgLoad = []
  4.  
  5. for(var i = 0; i < links.length; i++) {
  6. attachBehavior(links[i], i);
  7. }
  8.  
  9. function attachBehavior(obj, iter) {
  10.  
  11. var img = obj.getElementsByTagName('img')[0];
  12. var imgSrc = img.getAttribute("src");
  13. var ext = imgSrc.match(/\.\S{3}$/);
  14. var overSrc = imgSrc.replace(ext, "-over" + ext);
  15.  
  16. // preLoad over states
  17. imgLoad[iter] = new Image();
  18. imgLoad[iter].src = overSrc
  19.  
  20. // use event listeners if appropriate
  21. obj.onmouseover = function(){
  22. img.setAttribute("src", overSrc);
  23. }
  24. obj.onmouseout = function(){
  25. img.setAttribute("src", imgSrc);
  26. }
  27. }
  28. }
  29.  
  30. imageSwap("footer-links"); //all links inside the element with this id will receive mouseover behavior
  31.  
  32. /*
  33.   takes two image links "about.gif" and "about-over.gif" and swaps them on mouseover and mouseout
  34.   Any image link in HTML page that you want to recieve mouseover behavior make sure image exists that
  35.   has the name of the original image with "-over" appended to the end of the filename.
  36.   */

Report this snippet  

You need to login to post a comment.