jQuery: Livequery and the Hover Event CodeUnit 02 JAN 2011

Before jQuery’s native live() and delegate() functions came into being, the default for handling binding on late generated DOM elements was to make use of the excellent Brandon Aaron plugin LiveQuery (otherwise known as Live Query). Today we look at how one handles the hover event using a livequery declaration.

Now the standard way of using livequery is to simple attach the function call to the targeted element as such:

$('.mylink').livequery('click',function(){
alert('clicked');
});

However, because the hover event contains an implicit combination of the mouseover and mouseout functions, the livequery declaration for hover events looks considerably different:

$('.mylink').livequery(function(){
 $(this).hover(function() {
    $(this).addClass('hover');
 }, function() {
    $(this).removeClass('hover');
 });
 }, function() {
     $(this).unbind('mouseover').unbind('mouseout');
 }); 

And that’s is pretty much it. As you can see, you declare a standard full hover jquery function declaration as the first argument for the livequery function call. The second function call deals with the unbinding of the previously bound argument.

Not quite intuitive from the first glance, but it works like a bomb. In other words, nifty.

Related Link: http://brandonaaron.net/code/livequery/docs

Related Posts:

About Craig Lotter

Software developer, husband and dad to two little girls. Writer behind An Exploring South African. I don't have time for myself any more.