jQuery (Focus) Enter Leave Events

This is actually about two closely related plugins, that each add two special events to jQuery.

The first plugin is jquery.focusenterleave which adds the "focusenter" and "focusleave" events. These are to focusin and focusout what mouseenter and mouseleave are to mouseover and mouseout. That essentially means tabbed focussing does not bubble.

The second plugin (jquery.enterleave) combines these new events focus[enter|leave] with mouse[enter|leave] to form two new events, aptly named "enter" and "leave".

Demonstrations

Note that the events are attached to the blocks (span) not the inputs.

Download from Github (requires jQuery 1.3.2+
-earlier versions may work too!)

What's it for?

As with jQuery Action, I wanted a universal approach to the interface, whether the user wishes to tab through content or use the mouse.

jquery.enterleave is extremely handy when hiding/showing the user certain sections, to make sure that you show it whether they use a mouse or keyboard, and only hide it when they have really left. See the following example:

// append paragraph and input
$('#enterleave-example')
  .append( $('<p/>').text('Input appears and disappears on hover..') )
  .append( $('<input/>').attr({type:'text',value:'..but will not disappear if input is focussed!'}) );

// attach the events
$('#enterleave-example').bind('enter leave',function(){
  $('#enterleave-example>input').slideToggle();
});
#enterleave-example{
  width:50%;
  border:1px solid #333;
  padding:5px;
}
#enterleave-example>input{
  display:none;
}

Documentation

Implementation

The events work with jQuery functions such as jQuery.bind() .one() and so on. Shortcut methods have not been added e.g. there is no .enter()

Requires pairing

Although this may not be ideal, the leave events need to be paired with the equivalent enter event, so that the element has the correct properties to know that a leave has occurred. You can always add an empty function to them!

Misc

Apart from this issue (which could be worked-around if there is sufficient interest), there's nothing particular about these events you really need, they're pretty much like any event.
For the current state of an element, .data() is used for these self-explaining states (Boolean):

  • jquery.focusenterleave
    • "focusentered"
  • jquery.enterleave
    • "hasmouseenter"
    • "hasfocusenter"

◂ Back to the code section