Maybe the question is confusing but let me give you an example, when I spam click the button that toggles the width, the div with keep on animating way after the button press and it doesn't look amazing. What I want is for the div to stop midway and go the other way and not complete its existing animation when the button is pressed again.
$(document).ready(function() {
$('.menuToggle').click(function() {
$(".menuContainer").animate({
width: 'toggle'
});
});
});
.menuContainer {
height: 100px;
width: 50px;
float: left;
position: relative;
background-color: black;
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >
<!-- Menu Items -->
</div>
<h4 >Show Menu</h4>
Here is the fiddle, so you can see what exactly what I'm talking about. Try spamming the "Show Menu" button.
https://jsfiddle.net/x14usdga/5/
Help would be greatly appreciated, I have looked everywhere and I can't seem to find anything on my problem.
CodePudding user response:
You can use .stop()
method. Try this
$(document).ready(function() {
$('.menuToggle').click(function() {
$(".menuContainer").stop().animate({
width: 'toggle'
});
});
});
.menuContainer {
height: 100px;
width: 50px;
float: left;
position: relative;
background-color: black;
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >
<!-- Menu Items -->
</div>
<h4 >Show Menu</h4>
CodePudding user response:
You can check if element is not animated before do animation
https://api.jquery.com/is/
https://api.jquery.com/animated-selector/
$(document).ready(function(){
$('.menuToggle').click(function(){
if( $('.menuContainer').is(':animated') ) { return false; }
$(".menuContainer").animate({width: 'toggle'});
});
});
.menuContainer{
height: 100vh;
width: 15vw;
float: left;
position: relative;
background-color: black;
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >
<!-- Menu Items -->
</div>
<h4 >Show Menu</h4>