MicroTut: The jQuery Hover Method

0
0



When building a navigation menu, or any other jQuery script, it is often necessary to have a robust method with which to define a mouse over and mouse out state. This is where the hover() method comes along. Here is how it is used:

$('.selectorClass').hover(
function(){
    $(this).stop().fadeTo('slow',0.4);
},
function(){
    $(this).stop().fadeTo('slow',1);
});

This assigns the first function to be executed when the mouse moves above the elements on the page, which share the selectorClass class name, and the second one is executed when the mouse moves away.

You can use “this” inside of the functions, to access the element that triggered the event.

Hover actually binds the first function to the mouseenter event, and the second one to mouseleave, so you could alternatively write this:

$('.selectorClass').mouseenter(function(){
    $(this).stop().fadeTo('slow',0.4);
}).mouseleave(function(){
    $(this).stop().fadeTo('slow',1);
});

As of version 1.4 of jQuery, it is now possible to pass a single function to hover, which will be called on both mouseenter and mouseleave. This way you can shorten your code even more by writing only one function:

$('.selectorClass').hover(function(){
    this.check = this.check || 1;
    $(this).stop().fadeTo('slow',this.check++%2==0 ? 1 : 0.4);
});

The example above increments this.check every time the function is run. Depending on whether the number is even or not, it chooses the opacity level to pass to fadeTo() (1 being completely visible).

This is also a great place to use the jQuery toggle functions like .slideToggle() and .toggleClass().

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>