cosmo_kramer
cosmo_kramer

Reputation: 729

Dynamically created divs aren't clickable

Can't dynamically create a div with a clickable class:

HTML:

<div id="line1">
    <div class='clickMe'>old clickable text</div>
</div>

<div id="line2">
    <div class='dontClickMe'>old unclickable text</div>
</div>

<div id='button'>button</div>

Javascript:

$('.clickMe').click(function() {
    alert("foo");
});

$('#button').click(function() {
    $('#line2').html("<div class='clickMe'>new clickable text</div>");
});

Clicking the button replaces the code in line2. It looks fine in debugging tools, i.e. Chrome dev elements.

But the "new clickable text" in line2 is not clickable.

Upvotes: 0

Views: 233

Answers (2)

genesis
genesis

Reputation: 50982

Use .delegate()

var body = $("body");
body.delegate('.clickMe', 'click', function() {
    alert("foo");
});

Upvotes: 0

zzzzBov
zzzzBov

Reputation: 179256

Use delegate or live. Dynamically added divs wont have handlers bound unless you explicitly bind a new handler to them.

Upvotes: 3

Related Questions