Event Helpers
Prev Chapter 5. Events Next

Event Helpers

jQuery offers two event-related helper functions that save you a few keystrokes.

$.fn.hover

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.

Note

Prior to jQuery 1.4, the $.fn.hover method required two functions.

Example 5.13. The hover helper function

$('#menu li').hover(function() { 
    $(this).toggleClass('hover'); 
});

$.fn.toggle

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 5.14. The toggle helper function

$('p.expander').toggle(
    function() {
        $(this).prev().addClass('open');
    },
    function() {
        $(this).prev().removeClass('open');
    }
);


Copyright Rebecca Murphey, released under the Creative Commons Attribution-Share Alike 3.0 United States license.


Prev Up Next
Increasing Performance with Event Delegation Home Exercises