Mehdi Yeganeh
Mehdi Yeganeh

Reputation: 2129

Why click event don`t work when re-append element?

Why click event not work in this code (JSFiddle: http://jsfiddle.net/3WeP5/):

var holder = $("<div></div>");

$(document.body).append(holder);

var btn = $("<button>Click Here</button>");

btn.click(function(){alert('clicked');});

holder.append(btn);
holder.html("");
holder.append(btn);

you can replace this line:

btn.click(function(){alert('clicked');});

with (Not work again):

btn.bind("click",function(){alert('clicked');});

and if i dont use jquery and set javascript event like this, it works fine!!

btn[0].onclick=function(){alert('clicked');}

Why click event don`t work when i re-append element (button) and how can i fix it?

Upvotes: 4

Views: 2589

Answers (3)

iConnor
iConnor

Reputation: 20209

Try on jQuery ON

// You are better off just adding a id to the button

var btn = $("<button id=\"someButton\">Click Here</button>");

$(document).on('click', '#someButton', function(){
   alert('clicked');
});

What this does is add's a click listener to the document and when someone click's the document it checks to see if the event.target === btn

Here is a demo

The reason that the event's don't work is because jQuery.html(); removes the event listeners it is confirmed here https://github.com/jquery/jquery/blob/master/src/manipulation.js#L231

JSFiddle

Upvotes: 3

Jonathan Naguin
Jonathan Naguin

Reputation: 14796

Look the documentation of .html():

When .html() is used to set an element's content, any content that was in that element is completely replaced by the new content. Additionally, jQuery removes other constructs such as data and event handlers from child elements before replacing those elements with the new content.

holder.html(""); is removing the handler of the button. If you want to keep it you can use clone as:

holder.append(btn.clone(true));
holder.html("");
holder.append(btn.clone(true));

Upvotes: 6

Mohammad Areeb Siddiqui
Mohammad Areeb Siddiqui

Reputation: 10189

Use event delegation:

$(document.body).on('click', btn, function() {
    alert('clicked!');
});

Your code doesnot work because when the script if first loaded it binds the function to that particular element but when you add another one the script doesnot run again and so the appended element doesnot get its event binded. When we add event delegation, we target document.body and so when the script gets loaded event gets binded to that element on the body.

Demo.

For earlier versions of jQuery you may use this one:

$(document.body).delegate(btn, 'click', function() {
    alert('clicked!');
});

Upvotes: 1

Related Questions