Jquery How to Bind Onclick Event to Dynamically Added HTML Element

jQuery how to bind onclick event to dynamically added HTML element

The first problem is that when you call append on a jQuery set with more than one element, a clone of the element to append is created for each and thus the attached event observer is lost.

An alternative way to do it would be to create the link for each element:

function handler() { alert('hello'); }
$('.add_to_this').append(function() {
return $('<a>Click here</a>').click(handler);
})

Another potential problem might be that the event observer is attached before the element has been added to the DOM. I'm not sure if this has anything to say, but I think the behavior might be considered undetermined.
A more solid approach would probably be:

function handler() { alert('hello'); }
$('.add_to_this').each(function() {
var link = $('<a>Click here</a>');
$(this).append(link);
link.click(handler);
});

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>

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>

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>

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

Adding onClick event dynamically using jQuery

You can use the click event and call your function or move your logic into the handler:

$("#bfCaptchaEntry").click(function(){ myFunction(); });

You can use the click event and set your function as the handler:

$("#bfCaptchaEntry").click(myFunction);

.click()

Bind an event handler to the "click" JavaScript event, or trigger that event on an element.

http://api.jquery.com/click/


You can use the on event bound to "click" and call your function or move your logic into the handler:

$("#bfCaptchaEntry").on("click", function(){ myFunction(); });

You can use the on event bound to "click" and set your function as the handler:

$("#bfCaptchaEntry").on("click", myFunction);

.on()

Attach an event handler function for one or more events to the
selected elements.

http://api.jquery.com/on/

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/

The dynamically added click event gets fired many times

You're binding the click handler multiple times.

// on each click…
$('#btnAddRow').click(function() {
// bind a click event on body
$('body').on('click', 'li', function () {
alert($(this).text());
})
// ...
// bind a click event on every table
$('table').on('click', 'li', function () {
alert($(this).text());
})
})

As a result, every time your #btnAddRow is clicked you add two additional event handlers, one to body and another to all table elements.

How to add onclick to a html element dynamically using javascript

add an eventlistener to the element which has a defined function to call :

elem.addEventListener("click", func, false); //where func is your function name

https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener

Jquery: onclick event added to dynamically created li while parsing JSON is giving error when clicked

Try using this

$('#bullets').append('<li id="demo" onclick="loadCards(\'' + element.id + '\')">' + element.name + '</li>');

As exemplified by this fiddle:



Related Topics



Leave a reply



Submit