Youss
Youss

Reputation: 4232

Simple addClass on mouseover problem

I'm trying to set a class for a li item, with no luck. I have tried many things (to much to post) but I can't figure it out:

$("li").live("mouseover",function(){
    $(this).addClass('current');
});

The li item has to change class on mouseover(/hover) and keep that class state even if the mouse hovers outside the ul. But (and this is the tricky part) lose the class if another li item is hovered. Which means that the item being hovered gets the ''current'' class.

Hope it makes some sense..This is the fiddle jsfiddle

Upvotes: 0

Views: 766

Answers (3)

lonesomeday
lonesomeday

Reputation: 238115

You should remove the class from all the elements that currently have it before adding it to the new element:

$("li").live("mouseover", function() {
    $('.current').removeClass('current');
    $(this).addClass('current');
});

jsFiddle


For added optimisation (i.e. to save the $('.current') selection, which can be expensive in some older browsers), you could check to see if the element hovered already has the class:

$("li").live("mouseover", function() {
    if (!$(this).hasClass('current')) {
        $('.current').removeClass('current');
        $(this).addClass('current');
    }
});

Or, per Felix's excellent idea,

var current;
$("li").live("mouseover", function() {
    if (this !== current) {
        $(current).removeClass('current');
        $(this).addClass('current');
        current = this;
    }
});

jsFiddle

Upvotes: 3

Jeremy B.
Jeremy B.

Reputation: 9216

I've fixed it for you in the fiddle fiddle if you remove the current class from all the li elements and then apply it, you'll have better luck.

Upvotes: 2

James Montagne
James Montagne

Reputation: 78760

Just remove the class from its siblings:

$("li").live("mouseover",function(){
    $(this).addClass('current');
    $(this).siblings().removeClass("current");
  });

Upvotes: 2

Related Questions