As i know and understand that for dynamically created element, we need to write jquery function like
//.class is a element which is added dynamically in page using ajax call
$(".Class").on('click',function(){
//Code to execute here
alert("in here"); //not able to call it
})
but when i am trying to do it, i am not able to call this function.
Am i doing this correctly or something is wrong?
ok, i have faced this issue, and i can solve your problem quickly
you need to write function like this
//.class is a element which is added dynamically in page using ajax call?
$(document).on('click',".Class",function(){?
//Code to execute here?
alert("in here");· //not able to call it?
});
//that's it you are done
Important points
$("element")
element must be loaded with page, means instead of document
in above code you can replace it with any element id, which is loaded with page, and should be parent of dynamically added element(that is ".class" here)
You need to change your code like below to trigger on click
$(document).on('click',".Class",function(){
alert("Called in here");·
});
to fix this issue we need to call the on method on outer elements under which we append the elements dynamically and pass jquery selector as a second argument.
$(".Class").on('click',function(){})
one binds the event to all applicable elements present at the time of its execution and in second form it finds the applicable elements dynamically under the document object and triggers the click event.
jQuery Event binding on dynamically created elements works using .on after jQuery 1.7
Format looks something like this
$(staticElement).on(eventName, dynamicChild, function() {
//code to execute
});
This is called event delegation.
The event is attached to a static parent (staticElement) of the element.
For example, we have a html element and dynamic element inside it like this
<div class="mainElement">
<!-- <button>s that are generated dynamically and added here -->
</div>
Event Clicking to attach for dynamic element will be like this
$('.mainElement').on('click', 'button', function(){
// do something here
});
That's it.
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly