2

click not working after i clear and append the html inside a div using jquery. Here is the html code

<div id="divMain">
</div>
<input id="btn" type="button" value="Clear&Add"/>

Here is the jQuery code

var a = $('<a/>').attr({'id':'aH','href':'#'}).text('Hello');
a.click(function(){
    alert('hello');
});
$('#divMain').append(a);



$('#btn').click(function(){
   var newA = $('#aH');
    $('#divMain').html('');
    $('#divMain').append(newA);
});

Here is jsfiddle

Simple click on the alert link in fiddle , it shows an alert.Now click on the Clear&Add button .And now click on alert.It doesn't work.

iJade
  • 23,144
  • 56
  • 154
  • 243
  • [jQuery - Click event doesn't work on dynamically generated](https://www.google.com/search?q=jQuery+-+Click+event+doesn't+work+on+dynamically+generated) – VenomVendor Jan 01 '14 at 06:39
  • possible duplicate of [jQuery click not working for dynamically created items](http://stackoverflow.com/questions/9484295/jquery-click-not-working-for-dynamically-created-items) –  Jan 01 '14 at 06:43

3 Answers3

6

You need event delegation to bind the event with dynamically added elements. You also need to create elemet with id aH as you have removed the element from DOM without preserving it.

Live Demo

$(document).on('click', '#aH', function(){
    alert('hello');
});

You can try adding the globally created a and you would not need to bind click again.

$('#divMain').append(a);

Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers, jQuery api

Adil
  • 146,340
  • 25
  • 209
  • 204
0

You need to use event delegation:

$('#divMain').on('click', a, function(){
    alert('hello');
});

Updated Fiddle: http://jsfiddle.net/W95wV/1/

Felix
  • 37,892
  • 8
  • 43
  • 55
0

Click does not work on dynamically created elements in jQuery. In the earlier version of jQuery we could use .live('click') that has been deprecated in the recent versions. Now you can use .on to work better for dynamic elements as Adil said.

Manish Jangir
  • 5,329
  • 4
  • 42
  • 75