Event binding on dynamically created elements in JavaScript refers to the process of attaching event listeners to elements that are added to a webpage dynamically, meaning they are created or modified after the initial page load. This is a common scenario when you want to respond to user interactions on elements that are generated or updated dynamically, such as when new elements are added to a list or when existing elements are modified.
Let’s explore a few examples of event binding on dynamically created elements:
Example 1: Adding click event to dynamically created buttons
Suppose you have a webpage where users can add new buttons dynamically by clicking on a “Add Button” . You want each new button to perform a specific action when clicked. To achieve this, you can bind a click event to the newly created buttons as follows:
// Create a new button
const newButton = document.createElement('button');
newButton.textContent = 'Click me!';
// Bind a click event listener to the button
newButton.addEventListener('click', () => {
alert('Button clicked!');
});
// Append the button to the page
document.body.appendChild(newButton);
Example 2: adding click event listener to submitted form text
Imagine you want to capture the form submissions, and perform additional actions based on submitted value. We can add event listener to submitted text and can make ajax request or perform any additional logic to make changes to the page.