I’m trying to make it so that when a li element is hovered the background-position changes (which is working great) and when clicked it stays at the second active state (not working at all). It works if in the HTML the class “active” is applied to the element already. I’ve tried just about everthing I can think of and searched for a long time, but can’t seem to figure it out.
HTML:
<div id="navigation">
<ul>
<li><a href="#">Mission</a></li>
<li class="active"><a href="school.html">School</a></li>
<li><a href="programs.html">Programs</a></li>
<li><a href="instructors.html">Instructors</a></li>
<li><a href="contact.html">Contact Us</a></li>
<li class="bumpR"><a href="store.html">Store</a></li>
<li><a href="blog.html">Blog</a></li>
</ul>
</div> <!-- end navigation -->
jQuery:
$('#navigation li').not('li.active').mouseover(function() {
$(this).stop().animate({backgroundPosition: '0px -40px'}, 500);
// $(this).children('a').animate({opacity: .1}, 50);
$(this).children('a').css({ 'color': 'black'});
// $(this).children('a').delay(300).animate({opacity: 1}, 350);
})
$('#navigation li').not('li.active').mouseleave(function() {
$(this).stop().animate({backgroundPosition: '0px 0'}, 250);
//$(this).children('a').animate({opacity: .1}, 25);
$(this).children('a').css({ 'color': 'white'});
// $(this).children('a').delay(150).animate({opacity: 1}, 175);
});
$('#navigation li').click(function() {
$(this).addClass("active");
});
So for example hovering over “School” will correctly not animate the background position when the mouse leaves, but while clicking “Mission” will add the class “active” the mouseleave function still runs.
Any ideas why?
.mouseleave()binds the handler to every element in the set. At the time that the handler is bound, only one<li>has classactive, so only that element will not have themouseleavehandler bound.Instead, use
.live():or
.delegate():Edit
Fairly complete demo: http://jsfiddle.net/mattball/2mqSr/