Search

8/04/2008

Incoherent Babble » Blog Archive » Mouseenter and mouseleave events for Firefox (and other non-IE browsers)

Incoherent Babble » Blog Archive » Mouseenter and mouseleave events for Firefox (and other non-IE browsers)

The mouseenter and mouseleave events are similar to the more familiar mouseover/mouseout events, but with one important difference:

The mouseenter and mouseleave events don't bubble.

Now you might think then, that duplicating this effect is just a matter of stopping event propagation in non-IE browsers, but it's actually more complicated than that.

Of course you could achieve this same effect in non-IE browsers by stopping event propagation, but not by stopping it on the #theList (which is the element to which you'd be wiring up the mouseover/mouseout events).

No, you'd have to utilize .addEventListener(..) for each child element of #theList, hooking up functions to the mouseover/mouseout events that would take care of stopping the events from propagating (in this case bubbling) up to the parent element, and that would be a royal pain (not to mention that you might want the mouseover/mouseout events to bubble up for some (unrelated) reason).


function addEvent(_elem, _evtName, _fn, _useCapture){
if (typeof _elem.addEventListener != 'undefined')
{
if (_evtName === 'mouseenter')
_elem.addEventListener('mouseover', mouseEnter(_fn), _useCapture);
else if (_evtName === 'mouseleave')
_elem.addEventListener('mouseout', mouseEnter(_fn), _useCapture);
else
_elem.addEventListener(_evtName, _fn, _useCapture);
}
else if (typeof _elem.attachEvent != 'undefined')
_elem.attachEvent('on' + _evtName, f);
else
_elem['on' + _evtName] = f;
}

function mouseEnter(_fn){
return function(_evt){
var relTarget = _evt.relatedTarget;
if (this === relTarget || isAChildOf(this, relTarget))
{ return; }
_pFn.call(this, _evt);
}
};

function isAChildOf(_parent, _child){
if (_parent === _child) { return false; }
while (_child && _child !== _parent){
_child = _child.parentNode; }

return _child === parent;
}

沒有留言: