JavaScript HTML DOM EventListener
window.addEventListener:
The window.addEventListener
method is a way to listen for events in the browser, such as user interactions (clicks, keystrokes), page load events, and more. This method attaches an event handler to the window
object or any HTML element so that a specific function executes when the event occurs.
- Syntax:
window.addEventListener(event, handler, options);
Example 1: Listening for the load
Event
The load
event fires when the whole page, including all dependent resources (like images), is fully loaded.
window.addEventListener('load', function() {
console.log('Page fully loaded');
});
In this example, the message “Page fully loaded” is printed in the console once the entire page and all its resources are loaded.
Example 2: Listening for the resize
Event
The resize
event triggers when the browser window is resized. This can be useful if you want to dynamically adjust your layout based on the window size.
window.addEventListener('resize', function() {
console.log('Window resized to: ' + window.innerWidth + ' x ' + window.innerHeight);
});
Here, each time the browser window is resized, it logs the new width and height.
Example 3: Listening for Click Events on a Button
You can attach addEventListener
directly to a specific HTML element, like a button.
HTML:
<button id="myButton">Click Me</button>
JavaScript:
document.getElementById('myButton').addEventListener('click', function() {
alert('Button was clicked!');
});
In this case, when the button with id="myButton"
is clicked, it will show an alert saying “Button was clicked!”
Example 4: Using once
Option to Remove Event Listener After First Execution
The once
option can be set to true
so that the event listener runs only once and then removes itself.
javascript
Copy code
window.addEventListener('scroll', function() {
console.log('This message appears only once on first scroll.');
}, { once: true });
After the first scroll event, this listener will automatically be removed.
Exercises & Assignments |
---|
No Content Found. |
Interview Questions & Answers |
---|
No Content Found. |