1

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?

0

4 Answers 4

10

try event delegation

$(document).on("click", ".delete", function() {
 alert();
});
Sign up to request clarification or add additional context in comments.

3 Comments

that works for the dynamically created comments, however it's stopped working for the staticly created comments (they're outputted by php before load) :/
i've put it in $(document).ready(function() { .. }); but i still have the same problem
oh, that was because i had another function suppressing it on the static comments, oops. :P all good now :) thanks so much
1

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/

Comments

0

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

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.