Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery: add event to newly created element

Tags:

jquery

events

I have added a new element via jquery. Now I want a function to trigger when the element is clicked. I know there are many answers to this, but they don't seem to work for me. Not sure what I am doing wrong here.

I have tried:

new_ele = "<a>click me</a>"
new_ele.click(function() {alert('xxxx');}); 
other_ele.append(new_ele);

This fails before the new_ele is appended.

I have also tried (instead of the second line above)

new_ele.onclick = function() { alert('blah'); };

This appends the element, but nothing happens when I click.

And

new_ele.on('click',function() {alert('ddd');});

This also fails before the element is appended.

like image 560
user984003 Avatar asked Oct 06 '12 06:10

user984003


People also ask

How do you bind change event in jQuery for dynamically added HTML element?

If you try to bind the elements that are dynamically added to the DOM using the click() method of jQuery, this will not work, because it only binds the click event to elements that exist at the time of the “binding”. To bind the click event to all existing and future elements, use jQuery's on() method.

How to bind event dynamically in jQuery?

When we want to bind any event to an element, normally we could directly bind to any event of each element using the on() method. Example 1: This example using jQuery on() method to add paragraph element dynamically.

How can write Click event for dynamically generated button in jQuery?

$(document). ready(function() { $(document). on("click","button . delete-row",function(){ // Do something when button is clicked }); });


2 Answers

Change it to:

new_ele = $("<a>click me</a>");
new_ele.click(function() {alert('xxxx');}); 
other_ele.append(new_ele);

In order to add a jQuery .click() handler, you need a jQuery object that you can call the .click() method on. Your code was trying to do:

"<a>click me</a>".click(function() {alert('xxxx');}); 

which obviously wouldn't work because there's no click method on a string. Instead, you need to turn that HTML string into an actual jQuery object by calling $() on it.

like image 150
jfriend00 Avatar answered Oct 05 '22 11:10

jfriend00


defined anywhere before or after .clickme is added to the dom. All you need to be sure is 'body' or any other element is already present in the DOM. The 2nd argument is a path to trigger.

$('body').on('click', 'a.clickme', function(e){
  e.preventDefault();
  console.log("clicked!");
});

$new_ele = $('<a href="#" class="clickme">click me</a>');
$("body").append( $new_elem );
like image 26
chovy Avatar answered Oct 05 '22 09:10

chovy