Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In jquery animate, how do I use a custom object instead of a div?

Tags:

jquery

My situation started like this: I wanted to animate the background image of a div, but it seems, with jquery I can't retrieve the individual positions of the background images(background-position). So I thought why not create a object and animate it's values then just put this values in the css, but i can't figure out how to quite do it yet. Here's what I tried.

var obj={t:0};
                $("#wrapper").animate({
                    obj:100 //I tried obj.t & t as well
                },1000,'linear',function(){},function(){
                    $("#wrapper").css({
                            'background-position':obj.t+"% 0%"
                        });
                });

Also another question I need to ask is, if the picture is really big, I mean about 4000x4000px, would it be better to set it as a background image and change the background position, or move around the div itself?

like image 999
Bluemagica Avatar asked Nov 29 '25 16:11

Bluemagica


1 Answers

You need to use the step function of the animate method, and more importantly you need to animate the actual object.. not the #wrapper element

var obj = {
    t: 0
};

$(obj).animate({ // call animate on the object
    t: 100 // specify the t property of the object to be animated
}, {
    duration: 1000,
    easing: 'linear',
    step: function(now) { // called for each animation step (now refers to the value changed)
        $("#wrapper").css({
            'background-position': now + "% 0%"
        });
    }
});

Demo at http://jsfiddle.net/gaby/yPq8s/1/

like image 116
Gabriele Petrioli Avatar answered Dec 02 '25 05:12

Gabriele Petrioli