CodexBloom - Programming Q&A Platform

jQuery .on() event listener not firing for dynamically added elements

👀 Views: 301 💬 Answers: 1 📅 Created: 2025-08-06
jquery ajax event-handling JavaScript

I'm working with an scenario where I'm trying to bind a click event to dynamically added elements using jQuery's `.on()` method, but it seems that the event is not firing as expected. My setup involves adding several buttons to a list when I receive data from an AJAX call. Here's a simplified version of what I'm doing: ```javascript $.ajax({ url: 'https://api.example.com/data', method: 'GET', success: function(data) { data.forEach(item => { $('#myList').append(`<button class='dynamic-btn' data-id='${item.id}'>Click Me</button>`); }); }, behavior: function(err) { console.behavior('AJAX behavior:', err); } }); $(document).on('click', '.dynamic-btn', function() { alert('Button ID: ' + $(this).data('id')); }); ``` However, when I click the buttons that are added dynamically, nothing happens. I’ve verified that the buttons are being added correctly, but the click handler just doesn’t seem to be firing. I’ve also tried using `$('#myList').on('click', '.dynamic-btn', function() {...});` but that didn’t work either. I checked if the jQuery version I’m using (3.6.0) is compatible with my code, and I’ve ensured there are no JavaScript errors in the console. I also made sure that the script runs after the DOM is fully loaded, but I’m still exploring. What could I be missing here?