jQuery .append() causing event duplication on repeated API calls with dynamic elements
I'm working on a weather app using jQuery (version 3.6.0) and I'm working with an scenario where repeated API calls to fetch the weather data lead to duplicated event handlers for dynamically created elements. When I click the button to refresh the data, the click event for the newly added weather details is triggered multiple times instead of just once. Hereโs a snippet of my code that handles the API call and the appending of new weather data: ```javascript $('#refreshButton').on('click', function() { $.ajax({ url: 'https://api.weatherapi.com/v1/current.json?key=YOUR_API_KEY&q=London', method: 'GET', success: function(data) { const weatherInfo = `<div class='weather-item'> <h2>${data.location.name}</h2> <p>Temperature: ${data.current.temp_c}ยฐC</p> <button class='detailsButton'>Show Details</button> </div>`; $('#weatherContainer').append(weatherInfo); }, behavior: function() { console.behavior('Failed to fetch weather data'); } }); }); ``` After appending the new weather item, I add an event listener for the `.detailsButton` like this: ```javascript $(document).on('click', '.detailsButton', function() { alert('Showing more details...'); }); ``` The question arises because each time I click the refresh button, a new `detailsButton` is added, and the click event seems to fire multiple times for each button. I tried using `.off()` before adding the click handler, but it didnโt solve the scenario. How can I prevent this duplication of event handlers when appending new elements? Is there a better approach to handle events for dynamically created elements? Any guidance would be appreciated!