Events
Events refer to specific actions or occurrences on a web page.
In a web browser, numerous events occur, such as when a user clicks a button, presses a keyboard key, or navigates through a page.
By smoothly handling events, you can enhance the interaction between the user and the web page, creating a more dynamic user experience.
Major Event Types
-
Mouse Events: Reacts to actions related to the mouse on a web page.
click
: When an element is clickedmouseover
: When the mouse hovers over an elementmouseout
: When the mouse leaves an element
-
Keyboard Events: Reacts to keyboard actions.
keydown
: When a key is pressedkeyup
: When a key is released
-
Form Events: Reacts to actions related to web forms.
submit
: When a form is submittedchange
: When the value of an input element changes
Adding Event Listeners
To make a specific element on a web page detect events, you need to add an event listener using the addEventListener
method.
How to Use the addEventListener Method:
const button = document.querySelector('button'); // Adding a 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 containing various related information is generated.
button.addEventListener('click', function (event) { console.log('Clicked element:', event.target); console.log('Click coordinates:', event.clientX, event.clientY); });
Event Delegation
This involves adding an event listener to a single parent element, allowing it to handle events from multiple child elements.
<ul id="itemList"> <li>Item 1</li> <li>Item 2</li> <li>Item 3</li> </ul>
JavaScript Example:
// Add an event listener to the ul element that wraps the li elements document.querySelector('#itemList').addEventListener('click', function (event) { if (event.target.tagName === 'LI') { alert(event.target.textContent + ' has been clicked!'); } });
Which of the following is the most appropriate to fill in the blank?
Lecture
AI Tutor
Design
Upload
Notes
Favorites
Help