tags:

views:

19

answers:

3

Hi,

I have a ul element with many li items:

<ul>
    <li></li>
    ...
</ul>

when the user hovers their mouse over an li element, I'd like show some hidden buttons on the li, when they stop hovering, hide the buttons again. Trying to use delegate:

$("#myList").delegate("li", "hover", function () {
    if (iAmHovered()) {
        showButtons();
    } else {
        hideButtons();
    }
});

the above gets called for both hover and 'un-hover'. How can I distinguish if it's a leave or enter though?

Also, I got this sample from this question: http://stackoverflow.com/questions/2591885/delegate-equivalent-of-an-existing-hover-method-in-jquery-1-4-2

in which Nick says:

This depends on [#myList] not getting replaced via AJAX or otherwise though, since that's where the event handler lives.

I do replace the contents of #myList though, using:

$("#myList").empty();

will that cause a problem?

Thanks

A: 

You can declare the handler function so that it pays attention to the event argument, and then check the type.

Pointy
+1  A: 

You need to test for the type of event, like this:

$("#myList").delegate("li", "hover", function ( event ) {
    if (event.type == 'mouseover') {
        showButtons();
    } else {
        hideButtons();
    }
});

Since there's only one handler to run for both events, we are checking to see which one fired, and running the appropriate code.

As opposed to binding hover directly to the element where it is able to accept two handlers for the two event types.

patrick dw
Cool thanks that works.
A: 

why using delegate ? Wouldn't it be easier by just grabing #mylist li and perform a trivial .toggle on it ?

tom_pl
I thought delegate was more efficient if you have lots of items. In my case I have like 100 list items that should all have the same behavior, so applying the delegate to the parent reduces the overhead (if I understand the jquery model for delegate at all that is).