Reputation: 1595
I'm kind of tired with Javascript long script for animation and decide to try jQuery, but it seems I'm stuck even at the simplest code.
CSS:
#menu {float: right; font: italic 16px/16px Verdana, Geneva, sans-serif;}
ul#nav {list-style: none;}
ul#nav li {float: left; padding-right: 10px;}
ul#nav li a {color: white;}
ul#subnav {float: right; list-style: none; padding: 0; display: none;}
ul#subnav li {float: left; padding: 10px 5px; white-space: nowrap;}
ul#subnav li a {color: white;}
Script:
$(document).ready(function() {
$('.nav').hover(function() {
$(this).find('#subnav').stop().animate({width:'toggle'},350);
});
});
HTML:
<div id="menu">
<ul id="nav">
<li class="nav">
<a href="#"><img src="images/icon-home.png" width="36" height="36"/></a>
<ul id="subnav">
<li><a href="#">Home</a></li>
</ul>
</li>
<li class="nav">
<a href="#"><img src="images/icon-signin.png" width="36" height="36"/></a>
<ul id="subnav">
<li><a href="#">Sign In</a></li>
</ul>
</li>
<li class="nav">
<a href="#"><img src="images/icon-register.png" width="36" height="36"/></a>
<ul id="subnav">
<li><a href="#">Create Account</a></li>
</ul>
</li>
<li class="nav" style="padding-right: 0;">
<a href="#"><img src="images/icon-mail.png" width="36" height="36"/></a>
<ul id="subnav">
<li style="padding-right: 0;"><a href="#">Contact Us</a></li>
</ul>
</li>
</ul>
</div>
Here's the sample page: http://v1n-vampire.com/dev/jq-animation-stuck
If you continue to hover on the nav from left to right then back to left, eventually the animation will stuck. How to solve this?
Upvotes: 0
Views: 106
Reputation: 27277
toggle
seems to lose its target width; when you stop the slide out animation, the temporary width
stays and is preserved by the slide in animation.
This seems to be the behavior of old versions of jQuery and appears to have changed from 1.7.1 (your version) to 1.7.2 (the next version available on jsfiddle)
If you can't upgrade, removing the stop()
should solve this. A better solution would be to clear the width
style manually before running the toggle:
$(this).find('#subnav').stop().css({width:""}).animate({width:'toggle'},350);
demo (1.6.4, no change, breaks): http://jsfiddle.net/rYnTQ/
demo (1.7.2, no change, works): http://jsfiddle.net/rYnTQ/1/
demo (1.6.4, reset fix): http://jsfiddle.net/rYnTQ/2/
Also, please, don't use duplicate IDs (change id="subnav"
to class="subnav"
and change the selectors accordingly). It breaks the specification and the expectations of many frameworks. In jQuery, $(selector)
will use getElementById
if it sees an ID selector => always returns at most one element.
Upvotes: 1