I have some code like this:
$('.play').on( 'click', function(){
console.log('click');
});
The .play
element is dynamically created with $('.game').html('<span class="paly">Play</span>')
method. However, I have nothing in my console log when I'm clicking on this span. What am I doing wrong?
Thanks.
PS: I am using jQuery 1.7.1
You can use the live() method to bind elements (even newly created ones) to events and handlers, like the onclick event.
To attach event handlers to the dynamically created button, we need to select the button with a class of btn and add an event listener of click . We're saying that onclick of the button, the p tag with a class of moreInfo should display block .
In vanilla JavaScript, you can use the document. createElement() method to programmatically create an HTML button element and set its required attributes. Then to append the button to a container, you can use the Node. appendChild() method.
Attaching the event dynamically className = 'dynamic-link'; // Class name li. innerHTML = dynamicValue; // Text inside $('#links'). appendChild(li); // Append it li. onclick = dynamicEvent; // Attach the event!
Don't use live()
- it has been deprecated. Instead use on()
, but use it on a parent element to delegate the event to, like this:
$('#parentOfPlay').on('click', '.play', function(){
console.log('click');
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With