tags:

views:

16

answers:

2

Need some help assigning a mouseover event to display some icons that start out hidden.

For every <li> in the ul, I have icons. When the user mouses over the <li> I want the span tag with a class called "icons" to be displayed. When the mouse out event occurs remove the class and/or just hide the span. The problem for me is how to assign event so just the span tag and its contents appear and disapear when the mouse hovers over the <li>.

Heres the HTML:

<ul id="nav">
     <li>Cat 1
          <span class="icons">
              <div>stuff here</div>
          </span>
     </li>
     <li>Cat 2
          <span class="icons">
              <div>stuff here</div>
          </span>
             <ul>
                 <li>Sub Cat 2A
                     <span class="icons">
                         <div>2A stuff here</div>
                     </span>
                 </li>
             </ul>  
     </li>
</ul>

Heres my jquery code.

$('#nav li').each(function(){

                //Add Background Shading o Mouseover to all Rows in the menu
                $(this).mouseover(function(){ 
                        $(this).addClass("background_grey").removeClass("icons"); 
                })

                $(this).mouseout(function(){ 
                        $(this).removeClass("background_grey").addClass("icons"); 
                });
        });

Thanks for the help.

+1  A: 

You don't need to use the each() function for this. The mouseout() and mouseover() functions will will apply to all elements returned by your selector.

$('#nav li').mouseover(function(){ 
    ...
}).mouseout(function(){ 
    ...
});

Now to access the span inside of the element which was hovered, you would use the find() function.

    $(this).find("span").removeClass("icons"); 

    $(this).find("span").addClass("icons"); 

Lastly, you should use mouseenter/mouseleave in preference to mouseover/mouseout since you don't want your hide event to fire when you enter the span element.

$('#nav li').mouseenter(function(){ 
    $(this).addClass("background_grey")
    .find("span").removeClass("icons"); 
}).mouseleave(function(){ 
    $(this).removeClass("background_grey")
    .find("span").addClass("icons"); 
});
Joel Potter
Thanks Joel. That's exactly what I needed. I didn't even think of using .find()....show's my noobie credentials. thanks again.
Ronedog
+1  A: 

You can shorten it all down using .hover(), .toggleClass() and .toggle() like this:

$('#nav li').hover(function(){
  $(this).toggleClass("background_grey").find(".icons").toggle(); 
});

This toggles the background class whether the .icons spans are shown on hover, the opposite on mouseout.

Nick Craver
+1. I always forget about hover.
Joel Potter