lumio
lumio

Reputation: 7585

Linear animation with jQuery and fixed step-number

I'm trying to animate the backgroundPositionY of an <div> element. What I try to do is to animate it linearly. Every step should be in between a fixed range.

For example:

step1: backgroundPositionY: 0 (192*0)
step2: backgroundPositionY: 192 (192*1)
step3: backgroundPositionY: 384 (192*2)

... and so on

My current code looks like the following:

$curtains = $("#unshredder-curtains");
$curtains.data('backgroundPositionY', -3456);
$curtains.animate({
    backgroundPositionY: 3648
    }, {
    duration: 2000,
    easing: "linear",
    step: function(now, fx) {
        var newTop = Math.floor(now / 192) * 192;
        $(fx.elem).css('backgroundPositionY', newTop+'px');
    }
});

But that does nothing. It just animates the background as it usually does. The steps are just ignored.

Does anyone know how to do that special animation?

Thanks :)

Upvotes: 2

Views: 749

Answers (1)

marclar
marclar

Reputation: 3046

I'd probably do something like:

var step = 192;
setInterval(function(){
    $('#unshredder-curtains').css('backgroundPositionY', function(i, val){
        var bgPosY = (parseInt(val) + step) + 'px';
        $(this).html('New position: ' + bgPosY);
        return bgPosY;
    });
}, 100);

You can see it in action here: http://jsfiddle.net/pr7cc/

Upvotes: 3

Related Questions