As you may have discovered while trying to run a click()
event on a jQuery-generated (appended) element, you can’t accomplish it using the standard jQuery method of attaching an event to an element.
For example, let’s say we append a button dynamically to another element using jQuery to control a particular user action, like closing/hiding something on the page:
$('#element').append('<div id="close">Close</div>');
Easy enough, until you’d like to actually run a click event on that #close
button. Neither of these will actually work as you’d expect them to:
$('#close').click( function() { // This won't work... });
$('#close').on('click', function() { // This won't work... });
Solution
The solution is to attach the click event to the document
, then pass the element you want the action attached to along to the function using the following method:
$('#element').append('<div id="close">Close</div>'); $(document).on('click', '#close', function() { // This will work! });
Let me just say you bro deserve a beer! Some people find solutions and won’t post them online but you have helped me after spending more than an hour trying to fix this annoying issue. Cheers!
Thank you so much for posting this!! I found your article after spending what seemed life forever to figure this out. Thanks again!
Thank you for the solution sir 🙂
Thank bro, you saved me time. God bless you
tku!!! god bless you my son
You my friend are a saint, every other solution I found was so hacky but this is beautiful. Thank you!
Just to confirm what every one else says, you are a god. much appreciated, best solution I could find in over 2 hours. Much Love
You are a legend! God bless you, you saint!
I love you and I want to have your babies
Man I had to find a solution for this and I did so for three days. Thanks, mate just thanks.
Thanks !
You are a God-sent.
Brow, you are my hero! I would s*ck youre toes if you want to x
These comments a fake and this is not a good way to handle this!
let new = $(”);
new.click(function(){
// this requires no id
})
$(‘#element’).append(new);
Thanks, buddy..You have save my day
Son of a gun
Wow, thank you so much…you were very smart! As has been said here, “you saved my day”.
thanks a lot. this really save me.
4 hours of my life lost to this problem. You legend. Thank you