Events
Events refer to specific actions or occurrences that happen on a web page.
In a web browser, various events occur such as the user clicking a button, pressing a keyboard key, or navigating the page.
By handling events smoothly, you can enhance the interaction between the user and the web page, creating a more dynamic web experience.
Main Event Types
-
Mouse Events: Respond to actions related to the mouse on the web page.
click
: When an element is clickedmouseover
: When the mouse hovers over an elementmouseout
: When the mouse leaves an element
-
Keyboard Events: Respond to keyboard actions.
keydown
: When a key is pressedkeyup
: When a key is released
-
Form Events: Respond to actions related to web forms.
submit
: When the form is submittedchange
: When the value of an input element changes
Adding Event Listeners
To make a specific element in a web page detect events, you need to add an event listener using addEventListener
.
Using the addEventListener Method:
const button = document.querySelector('button');
// Add click event listener to the button
button.addEventListener('click', function () {
alert('The button has been clicked!');
});
Event Object and Information
When an event occurs, an event object that contains various information related to the event is created.
button.addEventListener('click', function (event) {
console.log('Clicked element:', event.target);
console.log('Click coordinates:', event.clientX, event.clientY);
});
Event Delegation
Event delegation involves adding an event listener to a parent element and managing events generated by multiple child elements from that parent element.
<ul id="itemList">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
JavaScript Example:
// Add event listener to the ul element that contains li elements
document.querySelector('#itemList').addEventListener('click', function (event) {
if (event.target.tagName === 'LI') {
alert(event.target.textContent + ' has been clicked!');
}
});
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.