unobtrusive mouseover image swap with preloader


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

Needs 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"); //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


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.