CodexBloom - Programming Q&A Platform

jQuery .on() not triggering event handler on dynamically added elements in certain scenarios

👀 Views: 55 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-16
jquery event-handling dynamic-content JavaScript

I'm updating my dependencies and I'm working with an scenario where I attach an event handler using jQuery's `.on()` method, but the event does not trigger for dynamically added elements under specific conditions. I have a list of items, and when I click a button, new items are appended to the list. The event handler is supposed to fire on clicks of these new items. However, if I append items after a 5-second delay (using `setTimeout`), the click event doesn't fire for those new items. Here's the relevant code snippet: ```javascript $(document).ready(function() { $('#itemList').on('click', '.item', function() { alert('Item clicked: ' + $(this).text()); }); $('#addItem').on('click', function() { setTimeout(function() { $('#itemList').append('<div class="item">New Item</div>'); }, 5000); }); }); ``` I've checked to ensure that the `.item` class is correctly applied to the new elements. When I add the items instantly without a delay, the click works fine. I also confirmed that jQuery is properly included and there are no console errors. My jQuery version is 3.6.0. Could this be a timing scenario or something related to event delegation? Any insights would be appreciated!