views:

53

answers:

4

I have a span that includes an anchor and a span. Example below

<span id="x"><a id="a_in" href="">link</a><span id="x_in">x</span></span>

Now I am attaching a mousenter / mouseleave event on the span with id="x". When I mouse over the the span id="x" it triggers the mousenter / mouseleave that's fine. The problem is when I mouseover the span id="x_1" inside the parent span mouseleave gets triggered.

I want mousenter / mouseleave to be triggered only when I mouseenter or mouseleave the parent.

Any ideas how to avoid this?

A: 

you need cancelBubble() and stopPropagation().

See here: http://www.thedutchguy.com/article/javascript-prevent-event-bubbling-parent-child-when-fired.html

and also here: http://www.openjs.com/articles/prevent_default_action/

Moin Zaman
Hmm thanks...let me try
Argyris
+2  A: 

short answer: you can't avoid this, but you can determine that the mouseleave/enter only happens on the parent

function mouseleaveOrEnterHandler(e){
   e = e || window.event;
   var target = e.target || e.which;
   if(target.id=='x') {
      //do something here
   }
}
jerjer
thanks I will try this as well
Argyris
A: 

Just be specific in what event you want to fire on what element. If your using jQuery: $("span#x").hover(function() { //action logic for mouse enter }, function() { //action logic for mouse leave });

joshuafreelance
A: 

OK...thank you guys. The prob was on a new div that I was showing on the mouseenter which overlapped my SPAN X and triggered mouseleave.

Also...

MooTools features mouseenter and mouseleave because mouseover/mouseout sometimes just does not work as expected. Mouseenter only fires once you enter the element and does not fire again if your mouse crosses over children of the element.

...so pretty much it does what you guys are suggesting and it works fine. http://demos.mootools.net/Mouseenter

Just in case someone is looking for how to stop propagation using mootools...

$('myelement').addEvent('click', function (e) { var event = e || window.event; if (event.stopPropagation) { event.stopPropagation(); } else { event.cancelBubble = true; } });

Thank you for your help!

Argyris