I want to bind an event on elements which are dynamically created by ajax call. Some elements are already present and an event is binds with them when page loads. But when new elements created after ajax call then new elements lose their bindings.
I searched and found a very good solution. Jquery Event won't fire after ajax call
In this question "Jason Fingar" presented two solution to fix this
- the second solution is using an on method but it won't work for me
- the first method work but some issues
Here is the first solution he presented
"1) Encapsulate your "binding" code and call it both on page load and immediately after the element in question gets added back to the page. For example:"
$(document).ready(function(){
// bind event handlers when the page loads.
bindButtonClick();
});
function bindButtonClick(){
$('.myClickableElement').click(function(){
... event handler code ...
});
}
function updateContent(){
$.ajax({
url : '/ajax-endpoint.php',
data : {'onMyWay' : 'toServer'},
dataType : 'html',
type : 'post',
success : function(responseHtml){
// .myClickableElement is replaced with new (unbound) html
element(s)
$('#container').html(responseHtml);
// re-bind event handlers to '.myClickableElement'
bindButtonClick();
}
});
}
What problem I am facing? The event is bind with the new elements successfully but for the old elements or the elements which are loaded on page load, the event is bound twice. What is the problem with this?