CodexBloom - Programming Q&A Platform

jQuery .click() event not triggering as expected on dynamically created elements

👀 Views: 43 đŸ’Ŧ Answers: 1 📅 Created: 2025-07-07
jquery ajax event-delegation JavaScript

I'm stuck trying to I'm working with an scenario where my jQuery `.click()` event handler isn't triggering for buttons that are dynamically created. I'm using jQuery version 3.6.0 and the buttons are being added inside a container that is populated via an AJAX call. Here's what I have so far: ```javascript // Event delegation for dynamically added buttons $('#container').on('click', '.dynamic-button', function() { alert('Button clicked!'); }); // Function to add buttons dynamically function addButtons() { for (let i = 0; i < 5; i++) { $('#container').append('<button class="dynamic-button">Button ' + (i + 1) + '</button>'); } } // Simulate AJAX call and adding buttons $(document).ready(function() { // Simulating an AJAX call setTimeout(addButtons, 1000); }); ``` The alert works fine for the buttons that are already in the DOM, but nothing happens when I click the buttons added through the AJAX call. I've also tried using the `.on()` method directly after the buttons are created, but that didn't work either. No behavior messages appear in the console. Is there something I'm missing with event delegation or how I'm handling the dynamic content? Any suggestions would be appreciated! I'm developing on macOS with Javascript. Thanks for any help you can provide!