kritya
kritya

Reputation: 3362

jQuery click not working on appended dom

I appended some div like this :

var to = "Some content"
$("#key").append("<div class=\"cont\">"+to+"  <span ded="+ lastid +" class=\"\contspan\">X</span></div>  ");

Then i tried to bind a click on event on the div with class cont by doing this :

$('.cont').delegate('div', 'click', function() {
    $("#logger").html("click")
});

But this doesnt works ? Where have i been going wrong ?

EDIT: I tried to place a bacground color to the class cont And the color is there to show that class id added fine

Upvotes: 1

Views: 422

Answers (3)

Huske
Huske

Reputation: 9296

Try using .live() function instead of delegate.

$('.cont').live('click', function() {
    // var text1 = $(this).attr("ded");
    $("#logger").html("click");
}

Upvotes: 0

genesis
genesis

Reputation: 50976

You have no <div> in your .cont there

http://sandbox.phpcode.eu/g/1cbbd.php

<div id="key"> 

</div> 
<div id="logger"> 
</div> 
<script> 
var to = "Some content"; 
var lastid = "test"; 
$("#key").append("<div class='cont'>"+to+"<span ded='"+ lastid +"' class='contspan'>X</span></div> "); 
$('.cont').delegate('span', 'click', function() { 
    //var text1 = $(this).attr("ded"); 
    $("#logger").html("click") 
}); 
</script> 

Upvotes: 0

Richard Dalton
Richard Dalton

Reputation: 35793

You aren't using delegate quite right, try this:

$('#key').delegate('div.cont', 'click', function() {
    //var text1 = $(this).attr("ded");
    $("#logger").html("click")
});

You call the delegate method on the element that isn't going to change ('#key') and then pass it the selector for the dynamic element ('div.cont') as the first parameter.

Upvotes: 4

Related Questions