-1

I try to use the .on() jQuery function for call something when the <li> that I have, are hovered.

When I try to do something like this:

$("body").on({
            mouseenter: function () {
                console.warn('dansl\'body');
                //stuff to do on mouse enter
            },
            mouseleave: function () {
                console.warn('sorti');
                //stuff to do on mouse leave
            }
});

It works, i receive the messages when my body is hovered. But when i try to replace "body" by "li", it's not working anymore. How can I apply a .on() on a set of <li> ?

PS: My <li> are generated after the document load.

Superdrac
  • 1,208
  • 17
  • 29

3 Answers3

1

You need event delegation for attaching events to dynamically added dom:

Update: .hover() can not be used with .on(). You can instead use:

$("body").on({
mouseenter: function () {
    console.warn('dansl\'body');
    //stuff to do on mouse enter
},
mouseleave: function () {
    console.warn('sorti');
    //stuff to do on mouse leave
}
}, "li"); //pass the element as an argument to .on
Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125
  • I'd recommend to look for the closest static parent element of `
  • ` to make the code running faster.
  • – VisioN Jun 25 '14 at 14:59
  • @VisioN: i totally agree to that. But OP didnt provided the information that how does elements are added. – Milind Anantwar Jun 25 '14 at 15:00
  • 1
    It's not working... No error, nothin. – Superdrac Jun 25 '14 at 15:00
  • @MilindAnantwar i add the li on a static UL – Superdrac Jun 25 '14 at 15:01
  • 4
    Two problems: 1) `hover` maps to `mouseenter` and `mouseleave`, not `mouseover` and `mouseout`, 2) [`hover` cannot be used with `on()`](http://stackoverflow.com/questions/9827095/is-it-possible-to-use-jquery-on-and-hover). – Frédéric Hamidi Jun 25 '14 at 15:01
  • 2
    @FrédéricHamidi: thanks....seriously did not knew it. – Milind Anantwar Jun 25 '14 at 15:05
  • 1
    Ok it works thank you. As everybody say, perhaps that you should replace `body` by `ul` in your post. For access the direct parent. And for the future users which could have the same question. – Superdrac Jun 25 '14 at 15:11