You can do that, using jQuery's hover
:
$("selector_for_your_ul li").hover(
function() {
$(this).addClass("selected").siblings("li").removeClass("selected");
},
function() {
$(this).removeClass("selected");
}
);
Live example
That will switch the "selected" class to the li
that the mouse is over, and if the mouse leaves one li
and doesn't enter another, it will remove the class (no none of them will have the "selected" class). I think that's what you said you wanted, although it doesn't match up with having one of them already have the "selected" class at the outset.
If you just want to change it when someone mouses over an li
but not remove it when the mouse leaves an li
without entering another, use mouseenter
:
$("selector_for_your_ul li").mouseenter(
function() {
$(this).addClass("selected").siblings("li").removeClass("selected");
}
);
Live example
If you look up the mouseenter
event in various references, they'll tell you it's IE-specific. That's true, but it's so useful that jQuery emulates it on other browsers.
Update: You can change the siblings("li")
to siblings("li.selected")
in the above if you like, e.g.:
$(this).addClass("selected").siblings("li.selected").removeClass("selected");
That may make it slightly more efficient (not trying to remove a class from something that already has it). Here's the first example (with hover
) updated to do that; here's the second example (with mouseenter
) updated to do that.
Off-topic: But depending on which effect you want, you may be able to achieve it with CSS rather than with jQuery and a "selected" class. If you just want the li
highlighted when the mouse is actually over it (the hover
example above), rather than leaving the last li
highlighted (the mouseenter
example above), and if you don't need to support IE6, you can do it using the CSS :hover
pseudoclass:
selector_for_your_ul li:hover {
color: red; /* ...or whatever... */
}
Live example But again, that's only if you want the hover effect, and only if you don't need to support IE6 (which only allows :hover
on a
elements).
` is the one that the up/down arrows should target.
– David Tang Jan 16 '11 at 10:29s` into one then? `$('li').appendTo('ul:first')`. This would be the simplest solution.
– David Tang Jan 16 '11 at 10:38