Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Zoom an image with jQuery using .offset()

I've got a very simple bit of code. It changes the max-width of the image to give the illusion of zooming in. I am using jQuery's offset() with the mouse's coordinates so the user can pan the image.

http://jsfiddle.net/tmyie/YcbDM/

$('.image-container img').mouseover(function () {
    $(this).css('max-width', '200%');
    $(this).mousemove(function (e) {
        $(this).offset({
             top: e.pageY - 300,
            left: e.pageX - 300   
        });
    });
 });

This works exactly as I want it to, however, I'd like the pan to be reversed. Currently, if you move your cursor up, you see the bottom half of the image and vice versa. I've tried reversing the offset, like so:

             top: e.pageY + 300,
            left: e.pageX + 300 

But the image is removed from view completely.

If possible I'd like to avoid using a plugin for this.


1 Answers

Reversing e.pageX and e.pageY seem to achieve the effect you wanted fairly well

$('.image-container img').mouseover(function () {
    $(this).css('max-width', '200%');
    $(this).mousemove(function (e) {
        $(this).offset({
             top: -e.pageY,
            left: -e.pageX

        });
    });
 });

http://jsfiddle.net/zSjL9/

like image 147
Pete TNT Avatar answered Feb 05 '26 03:02

Pete TNT



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!