jQuery offers two event-related helper functions that save you a few keystrokes.
The $.fn.hover
method lets you pass one or two functions
to be run when the mouseenter
and mouseleave
events occur on an element. If you pass one function, it will be run for
both events; if you pass two functions, the first will run for
mouseenter
, and the second will run for
mouseleave
.
Prior to jQuery 1.4, the $.fn.hover
method required two
functions.
Example 4.13. The hover helper function
$('#menu li').hover(function() { $(this).toggleClass('hover'); });
Much like $.fn.hover
, the $.fn.toggle
method
receives two or more functions; each time the event occurs, the next
function in the list is called. Generally, $.fn.toggle
is used
with just two functions, but technically you can use as many as you'd
like.
Example 4.14. The toggle helper function
$('p.expander').toggle( function() { $(this).prev().addClass('open'); }, function() { $(this).prev().removeClass('open'); } );