Dynamically Added Elements Don't Trigger The Animation
- element 1
- element 2
Solution 1:
Dynamic elements don't trigger the callback, because there are no event listeners bound to those dynamic elements. If you want to handle events to elements that don't exist yet, or using a selector that will select elements that are added dynamically, you should delegate the event:
$(document).on('click', 'li', function()
{
//handle
});
This code binds a click listener on the document itself, and the callback will be invoked for every click that is registered, provided that li
element is a child of the element on which the listener is bound. For example:
<divid='foo'><divid='bar'><span> test</span></div><span> test2</span></div>
Consider this code:
var outer = $('#foo');
$('#bar').on('click', 'span', function()
{
outer.append($('<span>Added</span>'));
});
This will add spans to the foo
div every time the span inside the bar element is clicked. It will not be invoked when you click spans that aren't children of the <div id='bar'>
This code, however:
$('#foo').on('click', 'span', function()
{
console.log(this);
});
will react to clicks on all spans inside the <div id='foo'>
element. Dynamic and static alike, even the span inside the bar
div.
Basic rule-of-thumb: read these snippets like so:
$(document).on('click', 'div', function(){});
<scope><event><selector><callback>
on event in <scope> for elements matching <selector>, apply <callback>
Solution 2:
You can bind the element after it is rendered on the page. Use jquery bind function.
Post a Comment for "Dynamically Added Elements Don't Trigger The Animation"