I want to fire off a click programmatically on an element added via AJAX. How is that possible? This is makes it a bit of a special case because the element is not added to the due to being injected via AJAX.
Is there a proper way to achieve this?
I want to fire off a click programmatically on an element added via AJAX. How is that possible? This is makes it a bit of a special case because the element is not added to the due to being injected via AJAX.
Is there a proper way to achieve this?
Yes, it is possible and you can achieve that in to steps:
Attach the event by event-delegation
to the elements added by AJAX:
$('#wrapper').on('click', '.element', function() {
// Add your functionality here
});
Trigger the click programmatically:
$('.element').trigger('click');
The click will work now because you attach it by event-delegation
on the first step. Good luck!
do this
jquery:
$('#parent').on('click','#element',function(){
alert('clicked');
});
javascript:
document.getElementById("parent").addEventListener("click", function(e) {
if(e.target && e.target.id== "element") {
alert('clicked');
}
});
Learn more about event delegation
Note #element
is the id of your element,you can change #parent
with the closest tag that is not added by the ajax