This question already has an answer here:
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??
Try something like
You basically need to attach your events from a non-dynamic part of the DOM so it can watch for dynamically-created elements.
source: this post
if you created your elements dynamically(using javascript), then this code doesn't work. Because, .click() will attach events to elements that already exists. As you are dynamically creating your elements using javascript, it doesn't work.
For this you have to use some other functions which works on dynamically created elements. This can be done in different ways..
Earlier we have .live() function
but .live() is deprecated.This can be replaced by other functions.
Delegate():
Using delegate() function you can click on dynamically generated HTML elements.
Example:
ON():
Using on() function you can click on dynamically generated HTML elements.
Example:
I faced this problem a few days ago - the solution for me was to use .bind() to bind the required function to the dynamically created link.
I hope this helps.
You have to add click event to an exist element. You can not add event to dom elements dynamic created. I you want to add event to them, you should bind event to an existed element using ".on".
.delegate should work,too.
Do this:
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:
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: