If you're looking to control animations in jQuery, the stop()
method could be helpful.
The stop()
function is used to stop the currently-running animation on the matched elements.
Usage:
.stop( [clearQueue ] [, jumpToEnd ] )
For animations that are based on relative values (such as adding or subtracting margin), using stop(true,true)
will clear the queue and directly jump to the end of the current animation.
var hoverInOptions = {
'margin-left': '+=50px',
'font-size': '+=2px',
}
var hoverOutOptions = {
'margin-left': '-=50px',
'font-size': '-=2px'
};
$('#menu li').hover(
function() {
$(this).stop(true,true).animate(hoverInOptions, 200);
},
function() {
$(this).stop(true,true).animate(hoverOutOptions, 200);
}
);
#menu li {
display: block;
width: 150px;
height: 24px;
background-color: #FF9933;
border: 1px solid #309;
padding: 10px;
margin: 4px 10px;
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="menu">
<li>First item</li>
<li>Second item</li>
<li>Third item</li>
<li>Fourth item</li>
<li>Fifth item</li>
</ul>
On the other hand, if your animations use fixed values, by setting stop(true,false)
, the next animation will seamlessly continue from where the last one left off without jumping to its end.
var hoverInOptions = {
'margin-left': '50px',
'font-size': '1.2em',
}
var hoverOutOptions = {
'margin-left': '10px',
'font-size': '1em'
};
$('#menu li').hover(
function() {
$(this).stop(true, false).animate(hoverInOptions, 200);
},
function() {
$(this).stop(true, false).animate(hoverOutOptions, 200);
}
);
#menu li {
display: block;
width: 150px;
height: 24px;
background-color: #FF9933;
border: 1px solid #309;
padding: 10px;
margin: 4px 10px;
cursor: pointer;
font-size: 1em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="menu">
<li>First item</li>
<li>Second item</li>
<li>Third item</li>
<li>Fourth item</li>
<li>Fifth item</li>
</ul>
An alternative approach to animating elements without JavaScript involves using CSS transition
:
#menu li {
display: block;
width: 150px;
height: 24px;
background-color: #FF9933;
border: 1px solid #309;
padding: 10px;
margin: 4px 10px;
cursor: pointer;
font-size: 1em;
transition: margin .2s, font-size .2s;
}
#menu li:hover {
margin-left: 50px;
font-size: 1.2em;
}
<ul id="menu">
<li>First item</li>
<li>Second item</li>
<li>Third item</li>
<li>Fourth item</li>
<li>Fifth item</li>
</ul>