Skip to main content
Practice

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

  1. Mouse Events: Respond to actions related to the mouse on the 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: Respond to keyboard actions.

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

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

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.

Using the event Object in addEventListener Callback
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.

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