Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery animate with setinterval

Tags:

jquery

my jQuery Code :

    $(document).ready(function(){
        setinterval(function(){
        $("#animate").animate({'margin-left':'50px'},1000)
        $("#animate").animate({'margin-left':'-50px'},1000)
        },2000); 

        });

HTML:

<div id="animate">sdfdsfdsfsdfsdfds</div>

I want to do animation that will go every 5 sec. What wrong ? Thanks !

like image 456
Arthur Chaykovski Avatar asked Dec 15 '22 11:12

Arthur Chaykovski


2 Answers

My preferred solution. This way, your animation will be 100% truly synchronous and will not suffer from overlapping animations. Trust me, while the other answers use setInterval() and it "looks" like it works, these solutions will inexplicably fail after enough iterations due to the asynchronous nature of javascript. Also, it only does one DOM lookup for the element and makes it a jQuery object just once as well.

jQuery(function($){
    (function swoop(element) {
        element
            .animate({'margin-left':'50px'}, 1000)
            .animate({'margin-left':'-50px'}, 1000, function(){
                setTimeout(function(){
                    swoop(element);
                }, 5000);
            });
    })($('#animate'));
});
like image 199
Brad M Avatar answered Jan 14 '23 06:01

Brad M


http://jsfiddle.net/3GHaf/

setInterval is case sensitive. Camel case it and it works.

like image 22
Stephen Fischer Avatar answered Jan 14 '23 08:01

Stephen Fischer