Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to bind .hover() to dynamically created "li" elemtent? [duplicate]

Tags:

jquery

All the solutions I was able to find suggests to use .live() method. But as of today it is deprecated.

.hover() works perfectly on "li" elements not created dynamically. But once I append new "li" .hover() is not triggered at all.

Anybody has figured this one out?

like image 692
Tadas V. Avatar asked Feb 19 '13 05:02

Tadas V.


1 Answers

The "hover" event has been deprecated with delegated event handling such as .on() per the .on() jQuery doc pages.

Instead, you need to use .on() delegated event handling with mouseenter and mouseleave and an event handler for each.

For example:

$(document).on("mouseenter", "li", function() {     // hover starts code here });  $(document).on("mouseleave", "li", function() {     // hover ends code here }); 

In your real code, you would select a static parent object that is much closer to the dynamic li tags than the document object for better performance.

like image 130
jfriend00 Avatar answered Sep 30 '22 10:09

jfriend00