A Magnifying Lens using Script and CSS

Tuesday, August 23, 2011

imageMagno is a something I put together because … well, just because. The idea is to provide a magnifying lens effect using a background image and background position animation. The lens tracks the position of the mouse, with a slight delay (debouncing, to be exact).

You can try it here: http://jsbin.com/adobuv (thanks to @austegard for putting up the jsbin).

The "magnifier" is an absolutely positioned div with borders curved to perfection.

function makeMagnifier() {
    var src = settings.src || img.attr("src");
    magnifier = makeEmptyDiv();
        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

When the mouse pauses, the magnifier animates to the new location.

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);
        left: e.pageX - (settings.size/2),
        top: e.pageY - (settings.size/2),
        "backgroundPosition": backLeft + "px " + backTop + "px"

Animating the background position of an element is not something jQuery can do without help. I used a plugin from Alexander Farkas.

EmanZBaltimore Tuesday, September 6, 2011
Great and thanks Scott!
Comments are closed.

My Pluralsight Courses

K.Scott Allen OdeToCode by K. Scott Allen
What JavaScript Developers Should Know About ECMAScript 2015
The Podcast!