How to add Javascript addEventListener on BrowserEvent

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 of 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 contain on each event object is different based on event types.

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

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

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

Example of Javascript addeventlistener click

Let 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 add event listener on Add button to increment num value.
  • Javascript add even listener on Subtract button to decrement num value.
  • Javascript onload eventListener on window object to initailize 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 num value, subtract button will decrement num value by click event and assign num value to 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 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 input value what we have typed, 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 it and to learn more 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 and are used tablet and mobile.
InputsEvents related to an input element.
FormClipboard
AnimationEvents occur when change in the animation state.
ClipboardEvents related to copy, 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

Spread the love

Leave a Comment

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

Scroll to Top