How to Attach Events to Dynamic HTML Elements With Jquery

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/

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().

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.

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).

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. You should use event delegation to handle the event.

 document.addEventListener('click',function(e){
if(e.target && e.target.id== 'brnPrepend'){
//do something
}
});

jquery makes it easier:

 $(document).on('click','#btnPrepend',function(){//do something})

Here is an article about event delegation event delegation article

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.

How to attach jQuery pop-up event to dynamically created HTML List

JSFiddle of Fix: https://jsfiddle.net/0phz61w7/

The issue is that you need to delegate the event. Please do the following:

Change:

pop.on('click', function(e) {
pop.popover('toggle');
pop.not(this).popover('hide');
});

To:

$(document).on('click', '.popbtn', function(e) {
pop.popover('toggle');
pop.not(this).popover('hide');
});

Also, you need to remove the } from line 54, just after console.log(x);. That is throwing an error.

The above modification works, but in the code provided, .popbtn is not visible because the node is empty. So in the jsfiddle provided, I added a CSS rule to include the text POPBTN. Click that and an alert I added to the click event fires.

Click event doesn't work on dynamically generated elements

The click() binding you're using is called a "direct" binding which will only attach the handler to elements that already exist. It won't get bound to elements created in the future. To do that, you'll have to create a "delegated" binding by using on().

Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time.

Source

Here's what you're looking for:

var counter = 0;

$("button").click(function() {

$("h2").append("<p class='test'>click me " + (++counter) + "</p>")

});

// With on():

$("h2").on("click", "p.test", function(){

alert($(this).text());

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>

<h2></h2>

<button>generate new element</button>

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>

Attach jquery events to dynamically created elements (jquery load php file)

You can use following code for this

$(document).on('click', '.emptab', function() {
var status = $(this).attr('id');
$("#employeedetails").load("employee.php", {'data': datastring, 'current': status});
});


Related Topics



Leave a reply



Submit