designosis
designosis

Reputation: 5263

better way to center-zoom images?

I put together a little jquery function to zoom in and out of an image on mouseover, while keeping the constraining box size constant.

Demo it here: http://jsfiddle.net/q9jHu/

It works great, but if you jiggle the cursor quickly between the images, it goes haywire. The script stores the size incorrectly when in mid-zoom. I've tried adding .stop() to the equation, but can't seem to fix the glitch.

I'm guessing I should store the data with .each() instead of on mouseover, but I don't know how to do this.

Any ideas?

Upvotes: 3

Views: 3501

Answers (2)

Jaspreet Chahal
Jaspreet Chahal

Reputation: 2750

Simplest one is to change

var $w = $(this).width();
var $h = $(this).height();

to

var $w = 120;
var $h = 180;

// static value

But cheery's solution is optimal

Upvotes: 0

Cheery
Cheery

Reputation: 16214

Look here http://jsfiddle.net/q9jHu/4/

$('.pixbox img').on({
    mouseover: function(){
        var $scale = 1.5;
        if (!$(this).data('w'))
        {
            $(this).data('w', $(this).width())
                   .data('h', $(this).height());
        }
        $(this).stop(true).animate({
            width:  $(this).data('w')*$scale,
            height: $(this).data('h')*$scale,
            left: -$(this).data('w')*($scale - 1)/2,
            top:  -$(this).data('h')*($scale - 1)/2
        }, 'fast');
    },
    mouseout: function(){
        $(this).stop(true).animate({
            width:  $(this).data('w'),
            height: $(this).data('h'),
            left: 0,
            top: 0
        }, 'fast');
    }
});

Upvotes: 8

Related Questions