I've written a small function that moves/bouces a button every 5 seconds like so:
HTML:
<a href="#" class="button">Text</a>
JS:
var interval;
function buttonShake(){
var times = 5;
var speed = 300;
var distance = '15px';
for(var i = 0; i < times; i++) {
twitterButton.animate({
left: '-='+distance
}, speed).animate({
left: '+='+distance
}, speed);
}
}
interval = setInterval(buttonShake, 4000);
What the button does it when clicked, it slides out a hidden box from the right hand side of the page. What I'm trying to do is prevent the button from bouncing once it has been clicked.
So I tried using the following
button.on('click', function(e){
// do the slideout animation
// add "open" class to the box
if(box.hasClass('open')){
clearInterval(interval);
}
});
The button
and box
elements have been defined correctly and the open
class is appended to the box once it slides out, however clearing the interval doesn't appear to be working. It still continuously calls the buttonShake()
function every 5 seconds.
Here is a JSFiddle with the full code for a live preview:
http://jsfiddle.net/30tsype8/3/
Am I doing something wrong here?
I noticed that if you leave it for a while, the animation seems to go into overdrive and rather than running for around 3 secs and pausing for a second before starting again, it just constantly bounces. I think jQuery is overlapping its calls and getting confused and stuck in a loop.
As you want to stop bouncing the button when they expand the panel, I would immediately finish the animation after the panel has expanded using
finish()
:Updated fiddle