CodexBloom - Programming Q&A Platform

jQuery .click() event not firing on dynamically generated list items after AJAX load

πŸ‘€ Views: 83 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-17
jquery ajax event-delegation JavaScript

I'm working with an scenario where I'm loading a list of items via an AJAX call, and I want to attach click events to these items using jQuery. The items are generated dynamically, but the click event doesn't seem to fire on them. I have verified that the AJAX call works properly, as the items are displayed on the page. However, when I try to click on any of the newly created list items, nothing happens. Here’s a snippet of what I’m doing: ```javascript $.ajax({ url: 'https://api.example.com/items', method: 'GET', success: function(data) { let list = $('#itemList'); list.empty(); $.each(data.items, function(index, item) { list.append(`<li class='item'>${item.name}</li>`); }); } }); $('.item').click(function() { alert('Item clicked: ' + $(this).text()); }); ``` The click event handler is defined before the AJAX call, and I thought that would bind the event correctly. I even tried using `.on('click', '.item', function() { ... });` to delegate the event, but that didn't resolve the scenario either. When inspecting the elements after the AJAX load, the items do have the class 'item', but the click event still doesn't trigger. I’m using jQuery version 3.6.0. Are there any known pitfalls with event delegation in this scenario, or do I need to adjust my approach? Any suggestions would be greatly appreciated. Has anyone dealt with something similar?