/ Published in: JavaScript
These functions allow you to set a handler for a mouseleave/enter event.
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
//These functions allow you to set a handler for a mouseleave/enter event //Note that the mouseout/over handler is always executed before the mouseleave/enter handler //Also note that mouseleave/enter events do not bubble; effectively, they don't bubble in this implementation either. //usage: elem.onmouseout = onMouseOutLeave(outHandler_or_null, leaveHandler); //usage: elem.onmouseover = onMouseOverEnter(overHandler_or_null, enterHandler); function onMouseOutLeave(handleOut, handleLeave) { return function(evt) { evt = evt || window.event; var ret = true; if(handleOut) ret = handleOut.call(this, evt); if(evt.type != "mouseout" || !handleLeave) return ret; var from = this; var to = evt.relatedTarget || evt.toElement; var tmp = to; do { if(tmp == from) return ret; //didn't leave; entered a child element tmp = tmp.parentNode; }while(tmp) return ret && handleLeave.call(this, evt); } } function onMouseOverEnter(handleOver, handleEnter) { return function(evt) { evt = evt || window.event; var ret = true; if(handleOver) ret = handleOver.call(this, evt); if(evt.type != "mouseover" || !handleEnter) return ret; var to = this; var from = evt.relatedTarget || evt.fromElement || this; //when the page loads, if the mouse is already inside the element and is then moved, the mouseover event fires. There is no source // element in that case so I set `from` to itself var tmp = from; do { if(tmp == to) return ret; //didn't enter; left a child element tmp = tmp.parentNode; }while(tmp) return ret && handleEnter.call(this, evt); } }