JAVASCRIPT
Attach and Detach Event Listeners to DOM Elements
Learn to add event listeners for user interactions like clicks or form submissions, and how to properly remove them to prevent memory leaks in your JavaScript applications.
const myButton = document.getElementById('myButton');
function handleClick() {
alert('Button was clicked!');
console.log('Button click event fired.');
}
if (myButton) {
myButton.addEventListener('click', handleClick);
console.log('Click event listener added.');
// To remove it later (e.g., after a certain condition or component unmount)
// myButton.removeEventListener('click', handleClick);
}
How it works: This snippet demonstrates how to attach an event listener to a button element using `addEventListener()`. When the button is clicked, the `handleClick` function is executed. It also includes a commented-out line showing how to use `removeEventListener()` to detach the function, which is crucial for memory management.