$(function(){ // Loop through all the sets of before and after pics $(".beforeafter").each(function(){ // Set the container's size to the size of the image $(this).width($(this).find("img[rel=before]").attr("width")).height($(this).find("img[rel=before]").attr("height")); // Convert the images into background images on layered divs $(this).append("
").find(".after").css({"background": "url(" + $(this).find("img[rel=after]").attr("src") + ")", "width": $(this).find("img[rel=after]").attr("width") + "px", "height": $(this).find("img[rel=after]").attr("height") + "px"}); $(this).append("
").find(".before").css({"background": "url(" + $(this).find("img[rel=before]").attr("src") + ")", "width": $(this).find("img[rel=before]").attr("width") - 40 + "px", "height": $(this).find("img[rel=before]").attr("height") + "px"}); // Add a helpful message $(this).append("
"); // Remove the original images $(this).find("img").remove(); // Event handler for the mouse moving over the image $(this).mousemove(function(event){ // Need to know the X position of the parent as people may have their browsers set to any width var offset = $(this).offset().left; // Don't let the reveal go any further than 50 pixels less than the width of the image // or 50 pixels on the left hand side if ((event.clientX - offset) < ($(this).find(".after").width() -14) && (event.clientX - offset) > 14) { // Adjust the width of the top image to match the cursor position $(this).find(".before").width(event.clientX - offset); } }); // Fade out the help message after the first hover $(this).hover(function(){ $(this).find(".help").animate({"opacity": 0}, 400, function(){$(this).find(".help").remove();}); }); }); });