Saturday, June 1, 2024
 Popular · Latest · Hot · Upcoming
16
rated 0 times [  22] [ 6]  / answers: 1 / hits: 119425  / 13 Years ago, tue, february 28, 2012, 12:00:00

I have a piece of jQuery that loops through each element in a given div( #container) and does a javascript alert each time a span is clicked. This works fine if the <span>'s are static.



However, if I use a piece of code like:



$(someLink).click(function(){
$(#container).html( <new html with new spans> )
});


The jQuery code doesn't fire off. Oddly enough though



My question is : Is there a reason my Click events don't work for dynamically created items? I assume I will have to add something into my document ready or heartbeat-script (which is fired every 100 miliseconds) to hook up the events??


More From » jquery

 Answers
61

Do this:


 $( '#wrapper' ).on( 'click', 'a', function () { ... })

$( 'body' ).on( 'click', '.your_dynamic_elem_css_selector', function () { ... }) # use body as wrapper static elem

where #wrapper is a static element in which you add the dynamic links.


So, you have a wrapper which is hard-coded into the HTML source code:


<div id="wrapper"></div>

and you fill it with dynamic content. The idea is to delegate the events to that wrapper, instead of binding handlers directly on the dynamic elements.




Btw, I recommend Backbone.js - it gives structure to this process:


var YourThing = Backbone.View.extend({

// the static wrapper (the root for event delegation)
el: $( '#wrapper' ),

// event bindings are defined here
events: {
'click a': 'anchorClicked'
},

// your DOM event handlers
anchorClicked: function () {
// handle click event
}

});

new YourThing; // initializing your thing

[#87162] Monday, February 27, 2012, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
irvinjovannix

Total Points: 416
Total Questions: 94
Total Answers: 117

Location: South Korea
Member since Sun, Aug 8, 2021
3 Years ago
;