mouseover image swap with preloader unobtrusive


/ Published in: JavaScript
Save to your folder(s)

Needs to include object detection to be completely unobtrusive


Copy this code and paste it in your HTML
  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");
  31.  
  32. // takes an image in html page of the form about_us_link.gif and swaps it with an image
  33. // about_us_link.gif and replaces it with image named about_us_link-over.gif
  34. // Create a new image for mouseover named the same as the original image
  35. // with "-over" appended to the end but before the extension for example

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.