Reputation: 7
This should be simple but cannot find the answer to this simple concept. In Jquery, I want to have a simple Jquery animation repeat itself after repeated clicks. ie to run on each click. I want the animation to run, then wait for a click before starting again from the beginning...I have tried resetting css height of the block in the callback of animate but this immediately takes the animation back to the beginning, I want it to wait till the next click before starting again.
my CSS is
<style>
.block {
background-color: red;
width: 100;
}
</style>
the HTML is
<div class="block">this is block </div>
<div id="go">go</div>
Jquery is
<script>
$(document).ready(function(){
$( "#go" ).click(function() {
$(".block").animate({height:"300px"}, "slow", "linear" , function(){
});
});
});
Upvotes: 0
Views: 1068
Reputation: 2984
A slightly different approach.
I've unbound the "click" immediately after the click, and then rebound the click at the end of the animation.
JS
var $mydiv = $('.mydiv');
var $clickme = $('#clickme');
$clickme.on('click', function() {
$clickme.off('click', '#clickme');
moveme();
});
function moveme()
{
$mydiv.animate( {width:"100px"}, "slow", "linear" ,
function(){
$mydiv.animate( {width:"50px"}, "slow",
function(){
$clickme.on('click', '#clickme');
});
});
}
It seems to work, BUT! It's possible to hit the button before the end of the animation and it will reanimate at the end of the cycle. I'll bet it has something to do with that darned queue that stores behavior in javascript. I'm still having problems understanding that queue. Perhaps an expert will chime in and straighten me out.
Upvotes: 0
Reputation: 1078
You can use the callback function on .animate, is this what you're asking for? Callback means after the animation is done, do something else
$(document).ready(function () {
$("#go").click(function () {
$(".block").animate({
height: "300px"
}, "slow", "linear", function () {
$(".block").animate({
height: "10px"
}, "slow", "linear");
});
});
});
Upvotes: 0
Reputation: 1015
Just reset it as the first stage of your onclick handler; something like this:
<script>
$(document).ready(function(){
$( "#go" ).click(function() {
//reset
$(".block").height("0px"); //adjust to whatever the height should be at the start
//run animation
$(".block").animate({height:"300px"}, "slow", "linear" , function(){
});
});
});
Upvotes: 1