Edupala

Comprehensive Full Stack Development Tutorial: Learn Ionic, Angular, React, React Native, and Node.js with JavaScript

How to add Javascript addEventListener on BrowserEvent

Javascript addEventListener

The Javascript addEventListener allows us to attach an event listener to the document or a DOM element that fires whenever an event occurs. This is the best approach for handling events in Javascript, as in the old times we use to add an inline event on elements.

In this article, we’ll learn how to use addEventListener, what are different events we can use, and at last, demonstrate a few examples of addEventListener.

What is Javascirpt addEventListener

Every time when a user, interacts with a DOM element, like a keypress, mouse move, scroll, and more, that time event is fire. An event can happen because of user interaction or generated by API to represent the progress of an asynchronous task.

We can attach and register an event handler to an HTML element like button, span, input, and div by using addEventListener. Events are normally used in association with functions or handlers and the function will not be executed before the event occurs (such as when a user presses a key).

We can think addEventListener is the replacement for the old approach of the event handler attribute and it recommends the approach to handling an event. We can add multiple handlers for the same event.

Event handlers
To react to events we can assign a handler – a function that runs in case of an event. Handlers is a way to run JavaScript code in case of user actions. There are several ways to assign a handler. Let’s see them, starting from the simplest one.

HTML-attribute
A handler can be set in HTML with an attribute named on<event>.

<input value=”Click me” onclick=”alert(‘Click’)” type=”button>

addEventListener
The EventTarget.addEventListener() method adds the specified EventListener-compatible object to the list of event listeners for the specified event type on the EventTarget on which it is called. The event target may be an element in a document, the Document itself, a Window, or any other object that supports events (such as XMLHttpRequest).

const button = document.getElementById('add');

button.addEventListener('click', ev => {
  console.log(ev);
}

Syntax of Javascript addEventListener

Each DOM event is represented by an object that is based on the Event interface. Information contained in each event object is different based on event types.

targetElement.addEventListener(eventType, listener);
targetElement.addEventListener(eventType, listener, options);
targetElement.addEventListener(eventType, listener, useCapture);

Let’s discuss the parameters we can pass and use in the addEventListener function.

  1. eventType: Is a type of event, in Javascript we have lots of event types like click, blur, and mousemove.
  2. listener: It serves as a listener for the event and handler function which is called in response to the event that occurs.
  3. useCapture: This is an optional value for controlling event propagation. By default is false for the bubbling phase and true for capturing phase.
  4. options Optional, An options object that specifies the characteristics of the event listener.

Example of Javascript addeventlistener click

Let’s demonstrate the addEventListener click example, here is a screenshot of our example.

javascript addeventlistener click

In this example, we add the event listener to the following elements.

  • Javascript adds an event listener on Add button to increment the num value.
  • Javascript adds even listener on Subtract button to decrement num value.
  • Javascript onload eventListener on window object to initialize num value to zero.

We have used the getElementById method to get references on buttons and p tag so that we can listen to events and assign value to the paragraph tag. The add button will increment the num value, subtract button will decrement the num value by clicking the event and assigning the num value to the paragraph tag with id=”number”.

<!DOCTYPE html>
<html>
<head>
    <script>
        let num;
        window.addEventListener('load', (event) => {
            num = 0;
            document.getElementById("number").innerHTML = num;
        });
    </script>
</head>

<body>
  <h4>Javascript addEventListener click</h4>
  <p>Number : <span id="number"></span></p>
  <p id="replaceString"></p>

  <button type="button" id="addBtn">Add</button>
  <button type="button" id="subBtn">Subtract</button>

  <script>
     document.getElementById("addBtn").addEventListener("click", () => {
       num++;
       document.getElementById("number").innerHTML = num;
     });

     document.getElementById("subBtn").addEventListener("click", () => {
       num--;
       document.getElementById("number").innerHTML = num;
     });

    </script>
</body>
</html>

Javascript mouseover and mouseout Example of Javascript addEventListener

In our second example, we’ll addEventListener of mouseover and mouseout over a section tags. When the user moves the mouse over the section tag it will add a background yellow and mouseout event will add white background. Here is a screenshot of the javascript mouseover and mouseout events.

javascript mouseover and mouseout example
Javascript mouseover and mouseout event
<!DOCTYPE html>
<html>
<head>
 <style>
  section {
    border: 2px dashed blue;
    margin: 10;
    padding: 10px;
    width: 300px;
   }
  </style>
</head>

<body>
  <section id="hover">
    <h4>Javascript mouse EventListener</h4>
    <p>Mouseover and mouseout event</p>
  </section>

  <script>
    hoverSection = document.getElementById('hover');
    hoverSection.addEventListener('mouseover', ev => {
      hoverSection.style.background = 'yellow';
    });

    hoverSection.addEventListener('mouseout', ev => {
            hoverSection.style.background = 'white';
    });
  </script>
</body>
</html>

Javascript addEventListener input event

In our last example, we’ll demonstrate the input event on input text by adding addEventListener. Whatever user type on input, we can listen to this event and we have taken its value and assigned it to the innerHTML of a paragraph element.

Javascript addEventListener
Javascript input event
<!DOCTYPE html>
<html>

<head></head>

<body>
    <section>
        <h4>Javascript input EventListener</h4>
        <input type="text" id="myInput">
        <p id="inputValue"></p>
    </section>

    <script>

        const input = document.getElementById("myInput");
        const inputValue = document.getElementById("inputValue");
        input.addEventListener('input', event => {
            inputValue.innerHTML = event.target.value;
        });
    </script>
</body>=
</html>

On our input event, the second argument event is the event object of input, to get the input value that we have typed, and can get from the event.target.value.

Javascript addEventListener types

We had demonstrated only three examples, Javascript has lots of events and here we had listed a few based on its types. We can classify this event based on its type and here we had listed some of them to learn more about events then check this link.

Event TypeDescription
mouseEvent-related to computer mouse, which we demonstrate two examples of it and it has many more.
KeyboardEvents related to the keyboard.
TouchEvents related to touch are used on tablets and mobile.
InputsEvents related to an input element.
FormClipboard
AnimationEvents occur when changing in the animation state.
ClipboardEvents related to copying, cut, and paste.
Network/ConnectionEvents related to network connect gain and lose
PrintEvent-related to the printer.

Javascript mouse events

The Javascript mouse has the following events.

  1. click – when the mouse clicks on an element (touchscreen devices generate it on a tap).
  2. contextmenu – when the mouse right-clicks on an element.
  3. mouseover / mouseout – when the mouse cursor comes over / leaves an element.
  4. mousedown / mouseup – when the mouse button is pressed/released over an element.
  5. mousemove – when the mouse is moved.

Javascript Form element events

Here we had listed some of the most common events on forms.

  1. submit – when the visitor submits a <form>.
  2. focus – when the visitor focuses on an element, e.g. on a <input>.

Javascript Keyboard events

  1. keydown When a user pushes a keyboard key.
  2. keyup – When a user presses and releases a key.
  3. keypress –  The keypress event is fired when a key that produces a character value is pressed down.

Related posts

How to add Javascript addEventListener on BrowserEvent

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top