user1469270
user1469270

Reputation:

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.

Upvotes: 3

Views: 406

Answers (1)

Pete TNT
Pete TNT

Reputation: 8403

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/

Upvotes: 1

Related Questions