Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

JavaScript Essentials - Events

Handling events in JavaScript

Events are actions or occurrences that happen in the browser. This tutorial covers how to handle events in JavaScript, allowing you to make your web pages interactive and dynamic.

Key Points:

  • Events are actions or occurrences in the browser.
  • Event listeners are used to handle events.
  • JavaScript provides many built-in event types.

Adding Event Listeners

Event listeners are used to handle events. You can add an event listener to an element using the addEventListener() method. Here is an example:


document.getElementById('myButton').addEventListener('click', function() {
    alert('Button clicked!');
});
                

HTML for the example button:



                

Common Event Types

JavaScript provides many built-in event types. Here are some common ones:

  • click - Fired when an element is clicked.
  • mouseover - Fired when the mouse pointer is moved onto an element.
  • mouseout - Fired when the mouse pointer is moved out of an element.
  • keydown - Fired when a key is pressed down.
  • keyup - Fired when a key is released.
  • load - Fired when the page has loaded.
  • resize - Fired when the browser window is resized.

Event Object

When an event is triggered, an event object is created. This object contains information about the event and provides methods to prevent default actions and stop event propagation. Here is an example:


document.getElementById('myButton').addEventListener('click', function(event) {
    alert('Button clicked!');
    console.log(event);
    event.preventDefault(); // Prevents the default action
    event.stopPropagation(); // Stops the event from bubbling up
});
                

Removing Event Listeners

You can remove an event listener using the removeEventListener() method. Here is an example:


function handleClick() {
    alert('Button clicked!');
}

document.getElementById('myButton').addEventListener('click', handleClick);

// Remove the event listener
document.getElementById('myButton').removeEventListener('click', handleClick);
                

Event Delegation

Event delegation is a technique where a single event listener is added to a parent element to handle events for multiple child elements. Here is an example:


document.getElementById('parent').addEventListener('click', function(event) {
    if (event.target && event.target.matches('button.btn')) {
        alert('Button clicked: ' + event.target.textContent);
    }
});
                

HTML for the example:


Summary

In this tutorial, you learned about handling events in JavaScript. You explored adding and removing event listeners, working with the event object, and using event delegation. Understanding these concepts is essential for creating interactive and dynamic web pages.