Search code examples
javascriptjqueryhtmlcssscale

jQuery UI .scale() effect producing odd positioning jumps


Fiddle here.

Description of problem:

I'm attempting to make this image scale into view (centered), and then give the appearance that it's "bouncing" away from the screen briefly after reaching its maximum size of 100%. Unfortunately, it is moving down and to the right with each new effect chain. Why?

Note that the effect I'm attempting to achieve is completely different from the bounce effect.


Solution

  • Try 'scale': 'box' option for scale effect.

    scale (default: "both")

    Type: String

    Which areas of the element will be resized: "both", "box", "content". Box resizes the border and padding of the element; content resizes any content inside of the element.

    As yours box div doesn't actually have any content, probably, that's the reason of unwanted shifts...

    Yours fiddle with modification.

    Another fiddle variant.

    Upd.

    As you can see in second fiddle, you can use separate function for each animation phase (effect). So, just in outermost phase pick current box size, and in each next phase calc scale percentage with honored current/initial box size, like following:

    var box = $('.box');
    box.data('size', {'w': box.width(), 'h': box.height()});
    box.show(scale_effect(box, 100, 250, function () {
        box.stop().effect(scale_effect(box, 80, 100, function () {
            box.stop().effect(scale_effect(box, 100, 100, function () {
                box.stop().effect(scale_effect(box, 90, 100, function () {
                    box.stop().effect(scale_effect(box, 100, 100, function () {
                    }));
                }));
            }));
        }));
    }));
    
    function scale_effect(box, percent, duration, complete) {
        box = $(box);
        var size = box.data('size');
        var absolutePercent = percent * size.w / box.width();
        console.log(absolutePercent);
        return {
            'effect': "scale", 
            'percent': absolutePercent,
            'scale': 'box',
            'duration': duration, 
            'queue': false,
            'complete': complete
        };
    }
    

    See the fiddle for preview.

    And here's some nifty variant with following syntax:

    $('.box').bouncedScale([
        {'percent': 100, 'duration': 250},
        {'percent': 80, 'duration': 100},
        {'percent': 100, 'duration': 100},
        {'percent': 90, 'duration': 100},
        {'percent': 100, 'duration': 100},
    ]);