CodeGym /Courses /Frontend SELF EN /Working with Events

Working with Events

Frontend SELF EN
Level 41 , Lesson 4
Available

5.1 Event Basics

Events in JavaScript allow you to interact with users and respond to their actions, like mouse clicks, key presses, form changes, and more. Understanding how to add and remove event handlers is a crucial part of developing interactive web applications.

What are events?

An event is a signal from the browser that something has happened. For example, a user clicked a button or a page loaded. Events allow you to perform certain actions in response to these signals.

Types of Events

There are many types of events. Some of the most commonly used include:

  • Mouse: click, dblclick, mouseover, mouseout, mousedown, mouseup, mousemove
  • Keyboard: keydown, keyup, keypress
  • Form: submit, change, focus, blur
  • Document/Window: load, resize, scroll, unload

Event Handlers

Event handlers (or event listeners) are functions that execute in response to a particular event. They "listen" for specific events and launch when those events occur.

5.2 Adding Event Handlers

Adding Event Handlers with addEventListener

The addEventListener method lets you add event handlers to elements. It provides more flexibility and control compared to traditional methods of adding events, like using HTML attributes (onclick, onchange, etc.).

Syntax:

    
      element.addEventListener(event, handler, options);
    
  

Where:

  • element: the element to which the event handler is added
  • event: the type of event to react to (e.g., 'click', 'input', 'keydown')
  • handler: the function that will be called when the event occurs
  • options: additional parameters (optional argument)

Example: Adding a click event handler

In this example, an event handler is added to a button. When the user clicks the button, an alert message appears.

HTML
    
      <!DOCTYPE html>
      <html>
        <head>
          <title>Event Example</title>
        </head>
        <body>
        <button id="myButton">Click me</button>

        <script>
          const button = document.getElementById('myButton');

          button.addEventListener('click', function() {
            alert('Button clicked!');
          });
        </script>
        </body>
      </html>
    
  

Example: Adding multiple event handlers

You can add multiple handlers for a single event with addEventListener.

In this example, two event handlers are added to the button. On click, both handlers execute sequentially, logging their respective messages to the console.

HTML
    
      <!DOCTYPE html>
      <html>
        <head>
          <title>Event Example</title>
        </head>
        <body>
          <button id="myButton">Click me</button>

          <script>
            const button = document.getElementById('myButton');

            button.addEventListener('click', function() {
              console.log('First handler');
            });

            button.addEventListener('click', function() {
              console.log('Second handler');
            });
          </script>
        </body>
      </html>
    
  

5.3 Using the options parameter

The options parameter lets you customize the behavior of the event handler. The most commonly used options:

  • once: if true, the handler executes only once and then automatically removes itself
  • capture: if true, the event is processed during the capture phase instead of the bubble phase
  • passive: if true, indicates that the handler will never call preventDefault()

Example: Handler that executes only once

In this example, the event handler will trigger only once, then be automatically removed.

HTML
    
      <!DOCTYPE html>
      <html>
        <head>
          <title>Event Example</title>
        </head>
        <body>
          <button id="myButton">Click me</button>

          <script>
            const button = document.getElementById('myButton');

            button.addEventListener('click', function() {
              alert('This will be shown only once');
            }, { once: true });
          </script>
        </body>
      </html>
    
  

5.4 Removing Event Handlers

Removing Event Handlers with removeEventListener

The removeEventListener method allows you to remove event handlers that were added with addEventListener. You need to pass the same arguments that were used when adding the handler.

Syntax:

    
      element.removeEventListener(event, handler, options)
    
  

Where:

  • element: the element from which the event handler is removed
  • event: the type of event whose handler needs to be removed
  • handler: the function that was assigned as the event handler
  • options: additional parameters (must match the parameters used when adding the handler)

Example: Removing a click event handler

In this example, a click event handler is added to a button. Pressing another button removes the click event handler.

HTML
    
      <!DOCTYPE html>
      <html>
        <head>
          <title>Event Example</title>
        </head>
        <body>
          <button id="myButton">Click me</button>
          <button id="removeButton">Remove Click Handler</button>

          <script>
            const button = document.getElementById('myButton');
            const removeButton = document.getElementById('removeButton');

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

            button.addEventListener('click', clickHandler);

            removeButton.addEventListener('click', function() {
              button.removeEventListener('click', clickHandler);
              alert('Click handler removed');
            });
          </script>
        </body>
      </html>
    
  
1
Task
Frontend SELF EN, level 41, lesson 4
Locked
Multiple Handlers
Multiple Handlers
1
Task
Frontend SELF EN, level 41, lesson 4
Locked
Removing an Event Listener
Removing an Event Listener
1
Survey/quiz
DOM Elements, level 41, lesson 4
Unavailable
DOM Elements
DOM Elements
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION