behz4d
behz4d

Reputation: 1847

jQuery on() method not working for appended elements

I know I should use on() method for triggering appended elements and not use click(), so:

$('#change_profile_img').on('click', function(){
alert(1);           
});

so the above code is working fine on any elements unless the appended elements, for example, I'm appending:

$('.companylogo:first').append('<a id="change_profile_img" class="ic_change">CHANGE IMAGE</a>');    

after it's appended, it's not working, but after a page refresh it works just fine. Another thing that I should mention, I'm doing the append from a modal page, it appends the button and everything but I could not trigger it anymore...

I would appreciate any kind of help. Thanks

Upvotes: 1

Views: 1975

Answers (5)

gilgimech
gilgimech

Reputation: 21

You can try delegating the click event when appending the element like this.

$('.companylogo:first')
    .append('<a id="change_profile_img" class="ic_change">CHANGE IMAGE</a>')
    .delegate('#change_profile_img', 'click', function(){
        alert(1);
});

Upvotes: 1

John Skoubourdis
John Skoubourdis

Reputation: 3289

This should work fine for you:

$(".companylogo").on("click", "#change_profile_img", function() {
  alert(1);
});

Upvotes: 2

behz4d
behz4d

Reputation: 1847

I have no idea why it's not working on this page, but finally I solved it by clearing the question a little bit! I put the appended elements on the page from the beginning, with the display='none', on the modal instead of appending them, I just show()ed them, and now everything is working out, thanks everyone

Upvotes: 0

suresh gopal
suresh gopal

Reputation: 3156

Please try this:

function GetIt()
{ 
    $('#change_profile_img').on('click', function(){
        alert(1);           
    });
}

You may call GetIt() function on body onload and each append time.

Upvotes: 0

Om3ga
Om3ga

Reputation: 32951

use it this way

$(document).on('click','#change_profile_img', function(){
    alert(1);           
});

Update

Check this DEMO

you are missing href in a tag

Upvotes: 2

Related Questions