I’m trying to make mouseenter work on Chrome, Firefox, etc. using the following function:
var addMouseenter = (function () {
var contains = function (parent, elem) {
return parent.contains ? parent.contains(elem) :
!!(parent.compareDocumentPosition(elem) & 16);
},
wrap = function (elem, method) {
return function (e) {
if (elem === e.target && !contains(elem, e.relatedTarget)) {
method.call(elem, e);
}
};
};
return function (elem, listener) {
var listener2 = wrap(elem, listener);
elem.addEventListener('mouseover', listener2, false);
};
}());
Everything worked fine until I ran into this specific situation:
- Element A has one of these custom
mouseenterlisteners - Element A contains Element B
- Element B is right up against the edge of Element A
- You enter Element A at that same edge
My expectation was that the mouseover event would be triggered on Element B and bubble up to Element A. However, that does not appear to be the case. I tested with Chrome 13 and Firefox 3.6 and got the same result. Did I mess something up?
The reason my custom function wasn’t firing is because it didn’t work.
I updated the fiddle showing that all is as it should be.
My mistake was only checking to see if
e.targetwas the same as the element I had attached the listener to. What I needed to be checking was if they were the same or ife.targetwas a child of the element.When you mouse over the two squares really quickly, it only registers the
mouseoverevent on the inner one, and because my listener was attached to the outer one, theelem === e.targettest was failing.So I changed the
ifcode in thewrapfunction to this: