Reputation:
I have an element nested in another element. I have a mouseover
event registered on the outer element. It fires both when my mouse enters the outer element, and when it enters the inner element. How can I turn off the event firing on the inner element?
Upvotes: 0
Views: 183
Reputation: 11149
Events fire on objects then bubble up the DOM tree. But you can stop them from bubbling with event.stopPropagation()
. This only works on standards-compliant browsers (not all but the most recent versions of IE).
innerElement.addEventListener('mouseover', function (event) {
event.stopPropagation();
}, false);
IE's version will be:
innerElement.attachEvent('onmouseover', function () {
window.event.cancelBubble = true;
});
So altogether:
function listener(event) {
event = event || window.event;
if (event.stopPropagation) {
event.stopPropagation();
} else {
event.cancelBubble = true;
}
}
if (innerElement.addEventListener) {
innerElement.addEventListener('mouseover', listener, false);
} else {
innerElement.attachEvent('onmouseover', listener);
}
Upvotes: 1
Reputation: 16951
Here is a possible solution:
el.onmouseover = function(e) {
//normalize event object to avoid cross browser inconsistencies
e = e || window.event;
//grab target element from which event is originated
var target = e.target || e.srcElement;
if (target === el) {
//do something here
}
};
If you use jQuery() it offers nice .hover() event which will handle such problems for you.
Upvotes: 1
Reputation: 413709
You can't turn it off, but your handler can always check event.target
(or event.srcElement
on IE) to make sure that it pertains to the correct one.
Alternatively, you can add a handler to the inner element and have it call "stopPropagation()" on the event object.
Upvotes: 0