Reputation: 75
I am trying to learn jQuery.I just tried to create a simple picture viewer with next and previous buttons using the basic show and hide.Hence the obvious flow of the script would be to first hide the previous image and then show the next image.But sometimes when I click the next button rapidly,it displays the next image without completing the .hide() of the previous. I need an elegant method to check whether the .hide() execution is complete or not and wait while its being done. Here's the code snippet
var picArray = new Array('#test1','#test2','#test3','#test4');
var picArrayIndex = 0;
$(document).ready(function()
{
$(picArray[picArrayIndex]).show();
$(".next-btn").click(function(){
picArrayIndex++;
if(picArrayIndex > picArray.length - 1)
{picArrayIndex = 0;
$(picArray[picArray.length - 1]).hide();
}
$(picArray[picArrayIndex - 1]).hide();
$(picArray[picArrayIndex]).animate({
opacity: 1,
hspace:80
}, 1000, function() {
// Animation complete.
});
$(picArray[picArrayIndex]).effect("bounce", { direction:'left', times:1 }, 500);
$(picArray[picArrayIndex]).show();
});
$(".prev-btn").click(function(){
picArrayIndex--;
if(picArrayIndex < 0)
{picArrayIndex = picArray.length - 1;
$(picArray[0]).hide();}
$(picArray[picArrayIndex + 1]).hide();
$(picArray[picArrayIndex]).show();
});
});
Upvotes: 0
Views: 3142
Reputation: 467
For complicated solutions I needed to use promise to ensure that hide is done, you could use this implementation:
$(obj).hide().promise().done(function (){ /* Your code goes here */ });
Upvotes: 0
Reputation: 2821
You can check in the hide callback:-
$(ele).hide("duration in milliseconds",function(){
//your code after hiding is done.
});
Upvotes: 2