Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot set click event handler on dynamically created content

Tags:

jquery

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

like image 242
bbrodriges Avatar asked Jan 13 '12 15:01

bbrodriges


People also ask

How do you bind a click event to dynamically created elements?

You can use the live() method to bind elements (even newly created ones) to events and handlers, like the onclick event.

How to add event listener to dynamically created element js?

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 .

How to create dynamic button click event in JavaScript?

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.

How to add event dynamically in js?

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!


1 Answers

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');
});
like image 97
Rory McCrossan Avatar answered Nov 02 '22 23:11

Rory McCrossan