/ Published in: JavaScript
Needs to include object detection to be completely unobtrusive
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
function imageSwap(id) { var links = document.getElementById(id).getElementsByTagName("a"); var imgLoad = [] for(var i = 0; i < links.length; i++) { attachBehavior(links[i], i); } function attachBehavior(obj, iter) { var img = obj.getElementsByTagName('img')[0]; var imgSrc = img.getAttribute("src"); var ext = imgSrc.match(/\.\S{3}$/); var overSrc = imgSrc.replace(ext, "-over" + ext); // preLoad over states imgLoad[iter] = new Image(); imgLoad[iter].src = overSrc // use event listeners if appropriate obj.onmouseover = function(){ img.setAttribute("src", overSrc); } obj.onmouseout = function(){ img.setAttribute("src", imgSrc); } } } imageSwap("footer-links"); // takes an image in html page of the form about_us_link.gif and swaps it with an image // about_us_link.gif and replaces it with image named about_us_link-over.gif // Create a new image for mouseover named the same as the original image // with "-over" appended to the end but before the extension for example