CodexBloom - Programming Q&A Platform

jQuery not triggering custom events on dynamically added elements

👀 Views: 40 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-17
jquery events dynamic-content javascript

I'm trying to figure out I'm having trouble with jQuery not triggering my custom events on elements that are added to the DOM dynamically... I'm using jQuery v3.6.0, and I have a setup where I create a button that, when clicked, adds a new div to the page and attempts to trigger a custom event on that div. However, the event listener I set up does not seem to catch the event for the dynamically added element. Here's the code I have: ```javascript $(document).ready(function() { // Event listener for the custom event $(document).on('myCustomEvent', '.dynamic-div', function() { console.log('Custom event triggered!'); }); // Button click to add a new div $('#addDivButton').click(function() { var newDiv = $('<div class="dynamic-div">New Div</div>'); $('body').append(newDiv); // Trying to trigger the custom event newDiv.trigger('myCustomEvent'); }); }); ``` When I click the button to add the new div, I can see the console log for the event listener not being triggered. The `console.log` statement inside the event handler never executes. I have verified that the new div is indeed added to the DOM, and I am using event delegation, so I thought it should work. Am I missing something in the way I'm triggering the event? Is there an scenario with the way I use the event delegation? Any insights would be greatly appreciated!