MouseEnter/Leave Handlers 2


/ Published in: JavaScript
Save to your folder(s)

These functions allow you to set a handler for a mouseleave/enter event.


Copy this code and paste it in your HTML
  1. //These functions allow you to set a handler for a mouseleave/enter event
  2. //Note that the mouseout/over handler is always executed before the mouseleave/enter handler
  3. //Also note that mouseleave/enter events do not bubble; effectively, they don't bubble in this implementation either.
  4. //usage: elem.onmouseout = onMouseOutLeave(outHandler_or_null, leaveHandler);
  5. //usage: elem.onmouseover = onMouseOverEnter(overHandler_or_null, enterHandler);
  6. function onMouseOutLeave(handleOut, handleLeave)
  7. {
  8. return function(evt)
  9. {
  10. evt = evt || window.event;
  11.  
  12. var ret = true;
  13. if(handleOut) ret = handleOut.call(this, evt);
  14.  
  15. if(evt.type != "mouseout" || !handleLeave) return ret;
  16.  
  17. var from = this;
  18. var to = evt.relatedTarget || evt.toElement;
  19.  
  20. var tmp = to;
  21. do
  22. {
  23. if(tmp == from) return ret; //didn't leave; entered a child element
  24. tmp = tmp.parentNode;
  25. }while(tmp)
  26.  
  27. return ret && handleLeave.call(this, evt);
  28. }
  29. }
  30. function onMouseOverEnter(handleOver, handleEnter)
  31. {
  32. return function(evt)
  33. {
  34. evt = evt || window.event;
  35.  
  36. var ret = true;
  37. if(handleOver) ret = handleOver.call(this, evt);
  38.  
  39. if(evt.type != "mouseover" || !handleEnter) return ret;
  40.  
  41. var to = this;
  42. var from = evt.relatedTarget || evt.fromElement || this;
  43. //when the page loads, if the mouse is already inside the element and is then moved, the mouseover event fires. There is no source
  44. // element in that case so I set `from` to itself
  45.  
  46. var tmp = from;
  47. do
  48. {
  49. if(tmp == to) return ret; //didn't enter; left a child element
  50. tmp = tmp.parentNode;
  51. }while(tmp)
  52.  
  53. return ret && handleEnter.call(this, evt);
  54. }
  55. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.