Listen to events for dynamically added DOM elements
In JavaScript, attaching event handlers on an element that is not yet created or does not exist on the page will throw an error. As a result, the event handler code won’t work. Fortunately, we can dynamically create an element in JavaScript and attach event handlers to it.
In jQuery, you can listen to events for dynamically added elements using the on()
function. The equivalent in JavaScript is addEventListener()
function.
Refer to the following code snippet to learn how to listen to events for dynamically added elements through jQuery and vanilla JavaScript.
// Listen to events for dynamically added elements using jQuery
$(document).on("click",'#signout-button', function(event) {
// Logout user.
});
// Listen to events for dynamically added elements using vanilla JavaScript
document.addEventListener("click", (event) => {
if(event.target && event.target.id == "signout-button"){
// Logout user.
}
});