6
votes

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.

7
"I am using jQuery 1.4.4, and as far as I know, I shouldn't need to use .live or .bind anymore." No, that's not true. When you use click or any of the other shortcuts for bind, you're dealing with whatever exists right then. The whole purpose of live and delegate is that you're explicitly saying "figure this out later when the event actually happens." - T.J. Crowder
Thanks TJ, for some reason I thought .live had been deprecated - pedalpete

7 Answers

12
votes

This works with jQuery 2.0.3

$(document).on('click', '#myDiv', function() {
    myFunc();
});
9
votes

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()

6
votes

You still need to use live events.

http://api.jquery.com/live/

4
votes

try
.on('event', 'element', function(){ //code })

2
votes

You need to use either live or delegate here. Nothing has changed in this department since jQuery 1.4.4.

Try to think of it like this: click and bind attach an event to the element itself, so when the element disappears, all the information about the event does too. live attaches the event at the document level and it includes information about which element and event type to listen for. delegate does the same thing, except it attaches the event information to whatever parent element you like.

0
votes

user "live" method $("div#star").live("click", function() {});

Doc

0
votes

You can use delegate instead on :

$(document).delegate('click', "selector", function() {
    //your code
});

I hope it will help.