Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery.click not working after adding element to the DOM

I have a simple jQuery('div#star').click(function.

The function works once when the DOM is initially loaded, but at a later time, I add a div#star to the DOM, and at that point the click function is not working.

I am using jQuery 1.4.4, and as far as I know, I shouldn't need to use .live or .bind anymore. There is never more than one div#star in the DOM at any one time. I tried changing from id="star" to class="star" but that didn't help.

Any suggestions on how to get this working or why it isn't working?

I've had the .click inside the jQuery(document).ready, and in an external js file, and neither works after adding the div to the DOM.

like image 831
pedalpete Avatar asked Feb 04 '11 17:02

pedalpete


2 Answers

This works with jQuery 2.0.3

$(document).on('click', '#myDiv', function() {
    myFunc();
});
like image 109
Emre Avatar answered Nov 15 '22 07:11

Emre


As of jQuery 1.7, the .live() method is deprecated. The current recommendation is to use .on() which provides all functionality covering the previous methods of attaching event handlers. Simply put, you don't have to decide any more since on() does it all.

Documentation is handily provided in the help for converting from the older jQuery event methods .bind(), .delegate(), and .live()

like image 39
Jason Avatar answered Nov 15 '22 08:11

Jason