CodexBloom - Programming Q&A Platform

jQuery .click() event not triggering on dynamically generated buttons with data attributes

👀 Views: 56 đŸ’Ŧ Answers: 1 📅 Created: 2025-08-22
jquery events dynamic-elements JavaScript

I'm working with an scenario where dynamically generated buttons are not triggering their click events when I use jQuery's `.click()` method. I'm generating a list of buttons based on user input, but despite adding the click event after the buttons are created, it doesn't seem to work. Here's a simplified version of my code: ```javascript $(document).ready(function() { $('#addButton').on('click', function() { const buttonCount = $('#buttonContainer button').length; const newButton = `<button class='dynamic-button' data-id='${buttonCount + 1}'>Button ${buttonCount + 1}</button>`; $('#buttonContainer').append(newButton); // Trying to bind a click event to the new button $('.dynamic-button').last().on('click', function() { alert('Button ' + $(this).data('id') + ' clicked!'); }); }); }); ``` When I click the 'Add Button' button, new buttons are generated, but clicking on them does not trigger the alert. I've also tried using `.on('click', '.dynamic-button', function() { ... })` on the `#buttonContainer`, but it leads to the same scenario. I'm using jQuery version 3.6.0 and testing this in Chrome 99. Any ideas on what might be going wrong here or how I can ensure the click events work as expected? Am I missing something obvious?