jquery.hoverIntent.js 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  1. /*!
  2. * hoverIntent v1.8.1 // 2014.08.11 // jQuery v1.9.1+
  3. * http://briancherne.github.io/jquery-hoverIntent/
  4. *
  5. * You may use hoverIntent under the terms of the MIT license. Basically that
  6. * means you are free to use hoverIntent as long as this header is left intact.
  7. * Copyright 2007, 2014 Brian Cherne
  8. */
  9. /* hoverIntent is similar to jQuery's built-in "hover" method except that
  10. * instead of firing the handlerIn function immediately, hoverIntent checks
  11. * to see if the user's mouse has slowed down (beneath the sensitivity
  12. * threshold) before firing the event. The handlerOut function is only
  13. * called after a matching handlerIn.
  14. *
  15. * // basic usage ... just like .hover()
  16. * .hoverIntent( handlerIn, handlerOut )
  17. * .hoverIntent( handlerInOut )
  18. *
  19. * // basic usage ... with event delegation!
  20. * .hoverIntent( handlerIn, handlerOut, selector )
  21. * .hoverIntent( handlerInOut, selector )
  22. *
  23. * // using a basic configuration object
  24. * .hoverIntent( config )
  25. *
  26. * @param handlerIn function OR configuration object
  27. * @param handlerOut function OR selector for delegation OR undefined
  28. * @param selector selector OR undefined
  29. * @author Brian Cherne <brian(at)cherne(dot)net>
  30. */
  31. ;(function(factory) {
  32. 'use strict';
  33. if (typeof define === 'function' && define.amd) {
  34. define(['jquery'], factory);
  35. } else if (jQuery && !jQuery.fn.hoverIntent) {
  36. factory(jQuery);
  37. }
  38. })(function($) {
  39. 'use strict';
  40. // default configuration values
  41. var _cfg = {
  42. interval: 100,
  43. sensitivity: 6,
  44. timeout: 0
  45. };
  46. // counter used to generate an ID for each instance
  47. var INSTANCE_COUNT = 0;
  48. // current X and Y position of mouse, updated during mousemove tracking (shared across instances)
  49. var cX, cY;
  50. // saves the current pointer position coordinates based on the given mousemove event
  51. var track = function(ev) {
  52. cX = ev.pageX;
  53. cY = ev.pageY;
  54. };
  55. // compares current and previous mouse positions
  56. var compare = function(ev,$el,s,cfg) {
  57. // compare mouse positions to see if pointer has slowed enough to trigger `over` function
  58. if ( Math.sqrt( (s.pX-cX)*(s.pX-cX) + (s.pY-cY)*(s.pY-cY) ) < cfg.sensitivity ) {
  59. $el.off(s.event,track);
  60. delete s.timeoutId;
  61. // set hoverIntent state as active for this element (permits `out` handler to trigger)
  62. s.isActive = true;
  63. // overwrite old mouseenter event coordinates with most recent pointer position
  64. ev.pageX = cX; ev.pageY = cY;
  65. // clear coordinate data from state object
  66. delete s.pX; delete s.pY;
  67. return cfg.over.apply($el[0],[ev]);
  68. } else {
  69. // set previous coordinates for next comparison
  70. s.pX = cX; s.pY = cY;
  71. // use self-calling timeout, guarantees intervals are spaced out properly (avoids JavaScript timer bugs)
  72. s.timeoutId = setTimeout( function(){compare(ev, $el, s, cfg);} , cfg.interval );
  73. }
  74. };
  75. // triggers given `out` function at configured `timeout` after a mouseleave and clears state
  76. var delay = function(ev,$el,s,out) {
  77. delete $el.data('hoverIntent')[s.id];
  78. return out.apply($el[0],[ev]);
  79. };
  80. $.fn.hoverIntent = function(handlerIn,handlerOut,selector) {
  81. // instance ID, used as a key to store and retrieve state information on an element
  82. var instanceId = INSTANCE_COUNT++;
  83. // extend the default configuration and parse parameters
  84. var cfg = $.extend({}, _cfg);
  85. if ( $.isPlainObject(handlerIn) ) {
  86. cfg = $.extend(cfg, handlerIn);
  87. if ( !$.isFunction(cfg.out) ) {
  88. cfg.out = cfg.over;
  89. }
  90. } else if ( $.isFunction(handlerOut) ) {
  91. cfg = $.extend(cfg, { over: handlerIn, out: handlerOut, selector: selector } );
  92. } else {
  93. cfg = $.extend(cfg, { over: handlerIn, out: handlerIn, selector: handlerOut } );
  94. }
  95. // A private function for handling mouse 'hovering'
  96. var handleHover = function(e) {
  97. // cloned event to pass to handlers (copy required for event object to be passed in IE)
  98. var ev = $.extend({},e);
  99. // the current target of the mouse event, wrapped in a jQuery object
  100. var $el = $(this);
  101. // read hoverIntent data from element (or initialize if not present)
  102. var hoverIntentData = $el.data('hoverIntent');
  103. if (!hoverIntentData) { $el.data('hoverIntent', (hoverIntentData = {})); }
  104. // read per-instance state from element (or initialize if not present)
  105. var state = hoverIntentData[instanceId];
  106. if (!state) { hoverIntentData[instanceId] = state = { id: instanceId }; }
  107. // state properties:
  108. // id = instance ID, used to clean up data
  109. // timeoutId = timeout ID, reused for tracking mouse position and delaying "out" handler
  110. // isActive = plugin state, true after `over` is called just until `out` is called
  111. // pX, pY = previously-measured pointer coordinates, updated at each polling interval
  112. // event = string representing the namespaced event used for mouse tracking
  113. // clear any existing timeout
  114. if (state.timeoutId) { state.timeoutId = clearTimeout(state.timeoutId); }
  115. // namespaced event used to register and unregister mousemove tracking
  116. var mousemove = state.event = 'mousemove.hoverIntent.hoverIntent'+instanceId;
  117. // handle the event, based on its type
  118. if (e.type === 'mouseenter') {
  119. // do nothing if already active
  120. if (state.isActive) { return; }
  121. // set "previous" X and Y position based on initial entry point
  122. state.pX = ev.pageX; state.pY = ev.pageY;
  123. // update "current" X and Y position based on mousemove
  124. $el.off(mousemove,track).on(mousemove,track);
  125. // start polling interval (self-calling timeout) to compare mouse coordinates over time
  126. state.timeoutId = setTimeout( function(){compare(ev,$el,state,cfg);} , cfg.interval );
  127. } else { // "mouseleave"
  128. // do nothing if not already active
  129. if (!state.isActive) { return; }
  130. // unbind expensive mousemove event
  131. $el.off(mousemove,track);
  132. // if hoverIntent state is true, then call the mouseOut function after the specified delay
  133. state.timeoutId = setTimeout( function(){delay(ev,$el,state,cfg.out);} , cfg.timeout );
  134. }
  135. };
  136. // listen for mouseenter and mouseleave
  137. return this.on({'mouseenter.hoverIntent':handleHover,'mouseleave.hoverIntent':handleHover}, cfg.selector);
  138. };
  139. });