views:

1935

answers:

3

I have an unordered list with mouseover and mouseout events attached to the li elements. Each contains a link and there is a bit of padding in the li. When I mouseover the li the mouseover event is fired, but when I mouseover the link contained in the li the mouseout and the mouseover events are both fired in order. It seems the child elements are firing their parent elements mouse events...how do I go about stopping this? I want it to just stay mouseovered when mousing over the links, not activating the animations every time I mouse over a link. This is my code;

 jQuery(document).ready(function(){
      jQuery('#menu li ul').hide();
      jQuery('#menu li').mouseover( function() {
           jQuery(this).children("ul").show('fast').stop;
           return false;
      });
      jQuery('#menu li').mouseout( function() {
           jQuery(this).children("ul").hide('fast').stop;
           return false;
      });
 });

 <ul id="menu">
      <li><a href="">Some link</a>
           <ul>Sub content</ul>
      </li>
 </ul>
A: 

Use css classes to distinguish the different menu levels. You can then easily search for one class or the other in your jQuery selectors.

Tomas Lycken
Unfortunately that would be overly difficult as this is for use with wordpress, which injects all of this dynamically and it's rather complicated to filter the output.
Stephen Belanger
+2  A: 

Use "event.stopPropagation()" to stop the events from bubbling upwards:

  jQuery('#menu li a').mouseover( function(evt) {
       evt.stopPropagation();
       return false;
  });
  jQuery('#menu li a').mouseout( function(evt) {
       evt.stopPropagation();
       return false;
  });

Alternatively use the mouseenter and mouseleave events instead of mouseover/out. jQuery normalizes their behaviour across browsers and these events have the benefit of not bubbling...

J-P
I've already tried that and it doesn't seem to be doing anything. I also tried using mouseenter and mouseleave and they don't do anything either.
Stephen Belanger
Okay, I wasn't *quite* right. It removes the mouseover from the link, but the mouseout is being called from the li element, not the link--so it's just flashing open and then closed again when I try to mouse over it.
Stephen Belanger
A: 

It seems I've found the answer to my own question. For anyone who might have the same problem; try this code instead. It seems hover doesn't bubble into child elements like the other mouse events do.

jQuery('#menu li').hover(
 function() {
  jQuery(this).children('ul').show('fast');
  return false;
 },
 function() {
  jQuery(this).children('ul').hide('fast');
  return false;
 }
);
Stephen Belanger