DEV Community

Ngan Kim Khong
Ngan Kim Khong

Posted on

4 3

addEventListener method

The addEventListener() method attaches an event handler to the specified element. Whenever the specified event is delivered to the target element,
the method addEventListener() sets up a function that will be called.

Basically, in an abstract way of saying, the server is just doing its things until the user (a human) interact with it by clicking something on-screen, pressing a button on the keyboard, or they could do anything that a computer is programmed to recognize.

Syntax:
target.addEventListener(event, function, useCapture);

Parameter:
type: Required. A STRING that specifies the name of the event.
You can find more event name as string here:
function: Required. Specifies the function to run when the event occurs.

When the event occurs, an event object is passed to the function as the first parameter. The type of event object depends on the specified event.

useCapture: Optional. A Boolean value that specifies whether the event should be executed in the capturing or in the bubbling phase.

Example:

You can add events of different types to the same element, in this case, the button.
document.getElementById("myButton").addEventListener("mouseover", myFunction);
document.getElementById("myButton").addEventListener("click", someOtherFunction);
document.getElementById("myButton").addEventListener("mouseout", someOtherFunction);

Using the optional useCapture parameter to show the difference between bubbling and capturing:
document.getElementById("myDiv").addEventListener("click", myFunction, false);
document.getElementById("myDiv").addEventListener("click", myFunction, true);

In this case, only the "true" value from useCapture can be run.

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs