Alex Mcp
Alex Mcp

Reputation: 19315

mouseover and addClass jQuery example

here's a gimme for anyone that knows jQuery:

I have a navigation <ul class="nav"> I want to change around. I'm basically looking for the a:hover effect, just faded in (I'm using sprites, and going from one sprite area to the next).

The code I have in my header looks like this:

$(document).ready(function(){
  $(".nav li").mouseover(function(){
    addClass('hovered');
  });
});

In my understanding of jQuery, this says "Once the document it ready, listen for a mouseover event on all .nav li elements. When you hear that, add a class "hovered" to it. So that's what I want to have happen, but right now -nothing- is happening.

Eventually I'll add in the animation and mouseOut, but I'd like to be able to get this part working as I want it. Thanks!

Upvotes: 1

Views: 13963

Answers (3)

graphicdivine
graphicdivine

Reputation: 11211

You're looking for the hover (http://api.jquery.com/hover/), and you need to target your LI with $(this):

$(document).ready(function(){
  $(".nav li").hover(function(){
    $(this).addClass('hovered');
  }, function(){
    $(this).removeClass('hovered');
 });
});

Upvotes: 4

alex
alex

Reputation: 490233

Just a tip, when you do eventually do something for mouseout, you can improve readability with

$(".nav li").hover(function() {
  // over
}, function() {
  // and out
});

... or as how I like to do it, use the jQuery plugin hoverIntent.

Upvotes: 0

Erik
Erik

Reputation: 20722

You have to give .addClass an element to work with.

$(this).addClass('hovered');

Upvotes: 2

Related Questions