Skip to main content
Crowdfunding
Python + AI for Geeks
Practice

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

  1. Mouse Events: Reacts to actions related to the mouse on a web page.

    • click: When an element is clicked
    • mouseover: When the mouse hovers over an element
    • mouseout: When the mouse leaves an element
  2. Keyboard Events: Reacts to keyboard actions.

    • keydown: When a key is pressed
    • keyup: When a key is released
  3. Form Events: Reacts to actions related to web forms.

    • submit: When a form is submitted
    • change: 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:

Using 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.

Using the event object in a callback function
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.

HTML: Elements for Event Delegation
<ul id="itemList">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>

JavaScript Example:

JavaScript: Example of Event Delegation
// 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!');
}
});

Want to learn more?

Join CodeFriends Plus membership or enroll in a course to start your journey.