views:

128

answers:

2

Hi all :)

I've just created a simple, continuous bounce effect in jQuery but I feel the code isn't all that optimized and am looking to improve it.

var $square = $("#square");
bounce();
function bounce() {
    $square.animate({
        top: "+=10"
    }, 300, function() {
        $square.animate({
            top: "-=10"
        }, 300, function() {
            bounce();
        })
    });
}

$square.hover(function() {        
    jQuery.fx.off = true;
}, function() {
    jQuery.fx.off = false;
});

All I've done is basically created an animation that adds +10 to the top coordinate of the element, and as a callback function, I'm subtracting 10 from the top coordinate..

This creates an (almost smooth) bounce effect but I feel it can be improved.

Furthermore, I want to stop the animation on mouseenter, and have it continue on mouseleave.

stop(true, true) didn't work, neither did dequeue() so I've resorted to turning all animation effects off using jQuery.fx.off = true (stupid, no?)

I'd appreciate any feedback on how this can be optimized.

Here's a jsFiddle.

EDIT: I've just realized that jQuery has started throwing too much recursion errors when disabling and re-enabling the effects.

Thanks in advance,

Marko

+3  A: 

Please try the below code Demo : http://jsfiddle.net/LMXPX/

$(function() {
    var $square = $("#square"),flag = -1;
    var timer;
    bounce();
    function bounce() {
        timer = setInterval(function() {
                   if(flag ==1) { 
                        flag = -1;
                    } else { 
                        flag = 1;
                    }
                    $square.animate({ top: "+="+(flag*10)}, 300)
                },300);
    }                

    $square.hover(function() {        
        clearInterval(timer);
    }, function() {
        bounce();
    });
});

Edit : I guess in your code multiple CallBack functions are the reason for too much recursion

Ninja Dude
So without the callback, is there another way to continuously loop the animation?
Marko
@marko If you had seen my answer, its not using callback
Ninja Dude
**smacks head** sorry, it's 9am and I just woke up :) That works perfectly, accepting.
Marko
A: 

Not much of an improvement but here's my attempt:

var $square = $("#square");

(function loop () {
    $square
        .animate({ top: "+=10" }, 300)
        .animate({ top: "-=10" }, 300, loop );
})();

$square.hover(function() {
    $.fx.off = !$.fx.off;
});

Marko Dumic
@Marko At first I thought of writing the same code, But it resulted in too much recursion, callBack function is the reason for too much recursion :(
Ninja Dude
Thanks @Marko - @Avinash's answer solved it! Hvala puno :)
Marko