Event binding on dynamically created elements?
As of jQuery 1.7 you should use jQuery.fn.on
with the selector parameter filled:
$(staticAncestors).on(eventName, dynamicChild, function() {});
Explanation:This is called event delegation and works as followed. The event is attached to a static parent (staticAncestors
) of the element that should be handled. This jQuery handler is triggered every time the event triggers on this element or one of the descendant elements. The handler then checks if the element that triggered the event matches your selector (dynamicChild
). When there is a match then your custom handler function is executed.
Prior to this, the recommended approach was to use
live()
:$(selector).live( eventName, function(){} );
However, live()
was deprecated in 1.7 in favour of on()
, and completely removed in 1.9. The live()
signature:$(selector).live( eventName, function(){} );
... can be replaced with the following on()
signature:$(document).on( eventName, selector, function(){} );
For example, if your page was dynamically creating elements with the class name
dosomething
you would bind the event to a parent which already exists (this is the nub of the problem here, you need something that exists to bind to, don't bind to the dynamic content), this can be (and the easiest option) is document
. Though bear in mind document
may not be the most efficient option.$(document).on('mouseover mouseout', '.dosomething', function(){
// what you want to happen when mouseover and mouseout
// occurs on elements that match '.dosomething'
});
Any parent that exists at the time the event is bound is fine. For example$('.buttons').on('click', 'button', function(){
// do something here
});
would apply to<div class="buttons">
<!-- <button>s that are generated dynamically and added here -->
</div>
Attach event to dynamic elements in javascript
This is due to the fact that your element is dynamically created, so it is attached to the DOM later, but your addEventListener
call already occurred in the past.
You should use event delegation to handle the event.
document.addEventListener("click", function(e){
const target = e.target.closest("#btnPrepend"); // Or any other selector.
if(target){
// Do something with `target`.
}
});
closest
ensures that the click occurred anywhere inside the target element or is the target element itself.This is useful if, for example, instead of your
<input id="btnPrepend"/>
you had a <button id="btnPrepend"><i class="icon">+</i> prepend</button>
and you clicked the <i class="icon">+</i>
.jQuery makes it easier:
$(document).on("click", "#btnPrepend", function(){
// Do something with `$(this)`.
});
Here is an article about event delegation. Adding an event to dynamically generated element using jQuery
Since the element is being generated dynamically, you need to use event delegation
.
$(document).on("click",".test", function () {
console.log("no");
});
Reference Document: https://learn.jquery.com/events/event-delegation/Hope this will help you.
Jquery how to bind click event on dynamically created elements?
here try this:
<script type="text/javascript">
$(function(){
$('body').on('click', '.pg_previous,.pg_next', function () {
jQuery("img.lazy").lazy({});
alert('ddsda');
});
});
</script>
How do I attach events to dynamic HTML elements with jQuery?
I am adding a new answer to reflect changes in later jQuery releases. The .live() method is deprecated as of jQuery 1.7.
From http://api.jquery.com/live/
For jQuery 1.7+ you can attach an event handler to a parent element using .on(), and pass the a selector combined with 'myclass' as an argument.As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers. Users of older versions of jQuery should use .delegate() in preference to .live().
See http://api.jquery.com/on/
So instead of...
$(".myclass").click( function() {
// do something
});
You can write...$('body').on('click', 'a.myclass', function() {
// do something
});
This will work for all a tags with 'myclass' in the body, whether already present or dynamically added later.The body tag is used here as the example had no closer static surrounding tag, but any parent tag that exists when the .on method call occurs will work. For instance a ul tag for a list which will have dynamic elements added would look like this:
$('ul').on('click', 'li', function() {
alert( $(this).text() );
});
As long as the ul tag exists this will work (no li elements need exist yet). jQuery event not triggering on dynamically created element
Ajax calls are asynchronous.
Before the elements are appended via ajax, the click handler gets registered, which find no elements with $(".off-del")
.
You should probably use event delegation.
$(document).on('click','.off-del',function(){
alert('hello');
var id= $(this).closest('tr').find($(":first-child")).html();
console.log(id);
});
Instead of $(document)
you can use a static parent. Add click event on a dynamically created element in Javascript
let div = document.createElement('DIV');
div.classList.add(".whatever");
div.addEventListener('click', function() {
console.log('dynamic elements')
});
document.body.appendChild(div);
https://jsfiddle.net/yu1kchLf/
Related Topics
Backbone: Why Assign '$('#Footer')' to 'El'
Getting a Union of Two Arrays in JavaScript
How to Find a Reason Angularjs "Argument 'Myctrl' Is Not a Function, Got Undefined"
Why Is 'This' Undefined Inside Class Method When Using Promises
How to Insert Variables in JavaScript Strings
Scope of Default Function Parameters in JavaScript
How to Pass Data from Child to Parent Component Angular
Cancel/Kill Window.Settimeout() Before It Happens
Angular Ui-Router $Urlrouterprovider .When Not Working When I Click <A Ui-Sref="...">
Single Plus Operator in JavaScript
How to Change the Pop-Up Position of the Jquery Datepicker Control
Convert Unix Timestamp to Date Time (Javascript)
How to Know When I'Ve Stopped Scrolling
How to Get Ssl Certificate Details Using JavaScript
Google Maps API Autocomplete 2Nd Address Fields on Same Page