Details
I have a function with animations inside, when clicking the button it will .append a div to the body. The div will then animate its position moving down a little bit. When another is added all of the divs will move down too so they will not overlap.
Now we run into the problem! When spamming the button to create the divs they will overlap.
How can we stop this from happening?
Notes:
- So only when the last function has completed all animations the next call can start
- Needs to remember and run the function how many time you clicked the button
- The function in my plugin has options that will need to be remembered (e.g the color of the background for the popup).
What I Have Tried
The way I see it is that I would like to create a queue for how many times you click the button and release the next in line after x amount of time has past (enough to finish all the animations). Problem is that I cannot find a way to do this in jQuery.
- I have looked into using
.queuein jQuery but fail to see a way this can help with this matter. - I have put a
setTimeoutonto the function but this causes a delay on the click
I feel like this is something very simple but I cannot find a solution after a few hours of messing around with it myself.
The Demo
I have created a demo for this question, my real version is a plugin so therefor is its own function. This is just a very basic version.
$("button").click(function() {
$("body").append("<div></div>");
$($("div").get().reverse()).each(function(index) {
$(this).animate({
top: "+=120px"
}, {
duration: 600,
queue: false
});
if (index >= 2) {
// Fade out and then remove the item
$(this).fadeOut("fast", function() {
$(this).remove();
});
}
});
});
div {
width: 400px;
height: 50px;
background: rgba(0, 0, 0, .4);
position: absolute;
top: 0;
right: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Click</button>