Posted By

cerxx on 08/27/18


Tagged

jQuery-plugin


Versions (?)

jQuery Hover Intent


 / Published in: JavaScript
 

URL: https://github.com/briancherne/jquery-hoverIntent/blob/master/jquery.hoverIntent.js

It is similar to jQuery's hover method. However, instead of calling the handlerIn function immediately, hoverIntent waits until the user's mouse slows down enough before making the call.

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

Report this snippet  

You need to login to post a comment.