Thursday, August 7, 2008

$.event.special.hover

A new and improved special event implementation Brian Cherne's "hoverIntent" plugin (http://plugins.jquery.com/project/hoverIntent).

Download - jQuery 1.2.6+ required.

This new "hover" event works like Brian Cherne's "hoverIntent" (http://plugins.jquery.com/project/hoverIntent), only better. When the cursor enters an element, the average speed of the mouse is checked asynchronously over a fixed delay interval. If the speed is below the specified limit, the "hover" event is triggered. This plugin leverages the special event api.

// bind a hover event handler $( elems ).bind( "hover", function(){ ... });

Additional related events can be handled.

  • hoverstart - is triggered on mouseenter and can return false to prevent "hover"
  • hover - is triggered between mouseenter and mouseleave when the mouse speed is below the specified limit, can return false to prevent "hoverend"
  • hoverend - is triggered on mouseleave only after "hover" has been triggered

The handlers for these events can be added/removed at any time, but the "hoverstart/hoverend" events will only fire while a "hover" handler is bound.

There are two parameters for controlling the hover event interaction. These values are captured at the time the "hover" event is bound, so for better or worse, changing these values in the global sense will not alter pre-existing bound hover events.

  • $.event.special.hover.delay (default: 100) - Defines the delay (milliseconds) while mouse is inside the element between speed checks.
  • $.event.special.hover.speed (default: 100) - Defines the maximum speed (pixels per second) the mouse may be moving to trigger the hover event.

A change (http://dev.jquery.com/changeset/5777) that should be included in 1.3 allows the passing of data from "bind" to the special event "setup" function. This change allows the parameters to be included from the bind method, using the existing, optional data argument.

// bind with data parameters (jQuery 1.3) $( elems ).bind( "hover", { speed:200, delay:200 }, function(){ ... });

Lastly, there is an overloaded jquery method called "hover" (Because a "hover" method already exists, this plugin renames the existing method "_hover" - If you have any problems with this, rename the new or old methods as you see fit). The method takes zero to three arguments.

// 0 args, trigger "hover" handler $( elems ).hover(); // 1 arg, binds "hover" handler $( elems ).hover( hoverFn ); // 2 args, binds "hover" and "hoverend" handlers $( elems ).hover( hoverFn, hoverendFn ); // 3 args, binds "hoverstart" and "hover" and "hoverend" handlers $( elems ).hover( hoverstartFn, hoverFn, hoverendFn );

Demo - Mouseover over the three blocks below... The blocks will only change color when the cursor speed is less than 100 pixels per second.

Please direct any feedback to http://groups.google.com/group/threedubmedia