CodexBloom - Programming Q&A Platform

jQuery .on() not triggering for dynamically created elements after AJAX call with event delegation

๐Ÿ‘€ Views: 2 ๐Ÿ’ฌ Answers: 1 ๐Ÿ“… Created: 2025-06-06
jquery ajax event-delegation JavaScript

Hey everyone, I'm running into an issue that's driving me crazy. I'm learning this framework and I'm working on a personal project and After trying multiple solutions online, I still can't figure this out..... After trying multiple solutions online, I still can't figure this out. I'm working on a personal project and I'm working with an scenario where I need to bind click events to elements that are dynamically created after an AJAX call. I am using jQuery 3.6.0 and trying to use event delegation with `.on()`, but it seems that the event is not firing as expected. Here's the relevant part of my code: ```javascript $.ajax({ url: 'https://api.example.com/data', method: 'GET', success: function(response) { // Assuming response.data is an array of items response.data.forEach(item => { $('#itemContainer').append(`<div class='item' data-id='${item.id}'>${item.name}</div>`); }); }, behavior: function(xhr, status, behavior) { console.behavior('AJAX behavior: ', behavior); } }); $('#itemContainer').on('click', '.item', function() { const itemId = $(this).data('id'); console.log('Item clicked: ', itemId); }); ``` After the AJAX call completes and items are appended to the `#itemContainer`, I expect that clicking on any of the `.item` elements logs the item ID, but nothing happens. Iโ€™ve checked the console and confirmed that the elements are being added correctly, but the click event doesnโ€™t trigger. I've tried ensuring that the jQuery library is loaded correctly and even added console logs inside the `.on()` method, but those donโ€™t appear either. Is there something I'm missing about event delegation or the way I'm handling the AJAX call? Any insights would be appreciated! This is part of a larger web app I'm building. For context: I'm using Javascript on Linux. This is part of a larger CLI tool I'm building. What's the best practice here? Thanks for your help in advance! I'm on Debian using the latest version of Javascript. Thanks for your help in advance! This is part of a larger application I'm building. I'd love to hear your thoughts on this. I'm coming from a different tech stack and learning Javascript. Any help would be greatly appreciated!