Goulash
Goulash

Reputation: 3838

jQuery .on("click"...) with dynamically created elements not working

So I am having some troubling results with jQuery ".on" function and a dynamically created element, the code I am using is this:

this is called in a function sometime random during runtime:

$(".activity-feed").append('<div class="feed-story big-feed-story feed-story-comment multiline-feed-story">\
        <div class="photo-view inbox-size photo-view-rounded-corners">\
            <div class="comment-icon">\
            </div>\
        </div>\
        <div class="comment-content">\
            <div class="delete ucomment-delete click-target" id="ucomment-'+uqid+'" tabindex="-1" style="outline:none;"></div>\
            <span class="feed-story-creator"><a href="/user/'+uid+'/'+username+'">'+username+'</a>&nbsp;</span>\
                <span class="comment-text">\
                    <span>\
                        <span style="white-space: pre-wrap;">'+$(".comment-box").html()+'</span>\
                    </span>\
                </span>\
            <div>\
                <span class="feed-story-footer"><span class="story-timestamp-view">'+time+'</span></span>\
            </div>\
        </div>\
    </div>');

and then this function should allow for comment deletion (its defined at the bottom of the page, not after document ready)

$(".delete").on("click", function() {
    alert('test....');
});

however, I click on the "ucomment-delete" button, and nothing happens :(, however if I click the comments that were there on load, it works
Why is this? What am I doing wrong?

Upvotes: 1

Views: 344

Answers (4)

Ringo
Ringo

Reputation: 5473

The .on() HAS to be wrapped in a document.ready(), even if it's at the end of the file. And I think what @John Koemer says is true, too.

Upvotes: 0

John Koerner
John Koerner

Reputation: 38077

You need to bind it to an element that already exists on the page and then can specify a selector for elements that may not yet exist on the page:

$(".activity-feed").on("click",".delete", function() {
    alert('test....');
});

See this fiddle for an example:

http://jsfiddle.net/G4MGZ/

Upvotes: 1

coolguy
coolguy

Reputation: 7954

if on is not working then your jquery version is older try delegate

$('body').delegate('.delete','click',function(){
 //stuff  
});

Upvotes: 0

Arun Killu
Arun Killu

Reputation: 14233

try event delegation

$(document).on("click", ".delete", function() {
 alert();
});

Upvotes: 10

Related Questions