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!'); } });
Lessons in this chapter ยท How does JavaScript work in the browser?
- 1. How Do Browsers Work?
- 2. DOM (Document Object Model)
- 3. Browser Window Object
- 4. Window - window.screen
- 5. Window - window.location
- 6. Methods to Select HTML Elements - 1
- 7. How to Select HTML Elements - 2
- 8. Creating and Setting Attributes of HTML Elements
- 9. Events
- 10. Advanced Event Handling
- 11. Multiple-choice quiz
- 12. JSON(JavaScript Object Notation)
- 13. Promise
- 14. Async/Await Handling Asynchronous Processes
- 15. Cookies
- 16. Multiple-choice quiz
- 17. JavaScript Summary
Which of the following is the most appropriate to fill in the blank?
Lecture
AI Tutor
Design
Upload
Notes
Favorites
Help