Reputation: 125
I have a CSS3 animation that jostles around at random when I click "Play". The problem is that I have been unable to stop the jostling when I click "Stop" which what I need to accomplish.
I have tried to use both the "-webkit-animation-play-state" and the jquery .stop() function but to no avail. I think I am close but just can't quite seem to get this one.
I have created a jsfiddle and the code is below.
Thanks in advance!
<html>
<head>
<style>
#sec {
background: url(http://placekitten.com/200/200);
background-repeat:no-repeat;
z-index: 3;
position: absolute;
width: 200px;
height: 200px;
top: 45px;
left: 105px;
}
</style>
<script>
$(document).ready(function(){
$("#play-bt").click(function(){
setInterval( function() {
var seconds = Math.random() * -20;
var sdegree = seconds * 2 ;
var num = -30;
var together = num + sdegree;
var srotate = "rotate(" + together + "deg)";
$("#sec").css({"-moz-transform" : srotate, "-webkit-transform" : srotate});
}, 100 );
});
$("#stop-bt").click(function(){
$("#sec").stop(stopAll);
})
})
</script>
</head>
<body>
<div id="sec"></div>
<br/>
<div id="play-bt">Play</div>
<br/>
<div id="stop-bt">Stop</div>
</body
</html>
Upvotes: 2
Views: 1546
Reputation: 17598
The counterpart of setInterval()
which is used to stop it is clearInterval()
. Each call to setInterval()
returns an interval ID, which you can pass to clearInterval()
to stop it.
So, you'll need to store the result of setInterval()
, and clear it when you click the stop btn.
$(document).ready(function(){
var animation = null;
$("#play-bt").click(function(){
if (animation !== null) { // Add this if statement to prevent
return; // doubled animations
}
animation = setInterval( function() {
var seconds = Math.random() * -20;
var sdegree = seconds * 2 ;
var num = -30;
var together = num + sdegree;
var srotate = "rotate(" + together + "deg)";
$("#sec").css({"-moz-transform" : srotate, "-webkit-transform" : srotate});
}, 100 );
});
$("#stop-bt").click(function(){
//$("#sec").stop(stopAll);
if (animation !== null) {
clearInterval(animation);
animation = null;
}
});
});
Upvotes: 2