Vitor Reis
Vitor Reis

Reputation: 989

Change CSS Class of All previous <li> when i hover some other item

what i need, might be quite simple to do with jQuery, I just suck at it :/

I have this Unordered List list of years, what i want to do is, to change ALL css classes of the previous List Items when I Hover another item.

For example, in this image below, if I place the mouse at "1904" I want to change the css class of 1901, 1902 and 1903.

alt text

Upvotes: 2

Views: 1069

Answers (1)

Nick Craver
Nick Craver

Reputation: 630379

You can use .prevAll() to get all previous siblings and then use .toggleClass() to add/remove a class on .hover(), like this:

$("li").hover(function() {
  $(this).prevAll("li").toggleClass("myClass");
});

You can give it a try here note that it doesn't style the hovered element, only the previous ones, if you want to style the hovered <li> as well, you can do this:

$("li").hover(function() {
  $(this).prevAll("li").andSelf().toggleClass("myClass");
});

In this case we're using .andSelf() to include the <li> being hovered in the set.

Upvotes: 10

Related Questions