Free Information Technology Magazines and eBooks

Wednesday, September 07, 2011

Create Magnifying Lens Using CSS and JQuery

I was impressed today by a cool css and script trick that creates a magnifying glass over a web page. The script provides magnifying lens effect using a background image and background position animation. The lens follows the mouse pointer position with a slight delay. Here a snippet from the whole code. It creates the magnifier effect:
   
function makeMagnifier() {
var src = settings.src || img.attr("src");
    magnifier = makeEmptyDiv();
    magnifier.css({
        position: "absolute", 
        opacity: 0,
        width: settings.size, height: settings.size,
        left: img.offset().left, top: img.offset().right, 
        "-moz-border-radius": settings.size * .5 + "px", 
        "border-radius": settings.size * .5 + "px",       
        "background-image": "url(" + src + ")",
        "background-repeat": "no-repeat",
        "z-index": 998
    });
}

Script to follow the mouse pointer with delay.
    
function onPosition(e) {
    var offset = img.offset();
    var backLeft = Math.round((e.pageX - offset.left) * 
                             (-1 / settings.scale));
    var backTop = Math.round((e.pageY - offset.top) * 
                             (-1 / settings.scale));
    backLeft += Math.round(settings.size / 2);
    backTop += Math.round(settings.size / 2);
    magnifier.animate({
        left: e.pageX - (settings.size/2),
        top: e.pageY - (settings.size/2),
        "backgroundPosition": backLeft + "px " + backTop + "px"
    });            
}
See the code in action here
Download the complete source code here. 


To stay up-to-date on Coding Tips & Tricks, subscribe now.

0 comments: