How to Use addEventListener Method in JavaScript

01/05/2022

Contents

In this article, you will learn how to use addEventListener method in JavaScript.

Basic usage of addEventListener

Below is the syntax of addEventListener.

element.addEventListener(event type, function, false);

You can specify 3 arguments in all.

First argument

In the first argument, specify the event type you want to process.
For the event type, specify the type such as mouse click or keyboard input.

Second argument

In the second argument, specify the processing content to be executed when the event specified in the event type occurs.

Third argument

You can specify the timing to receive the event in the third argument.

List of main event types in addEventListener

Resource event

EventDescriptionBubblesCancelable
loadThe event is fired when the entire resource has been loaded.nono

View event

EventDescriptionBubblesCancelable
resizeThe event is fired when the view (browser display area) is resized.nono
scrollThe event is fired when the view or element is scrolled.yesno

Mouse event

EventDescriptionBubblesCancelable
clickThe event fires when the user clicks on the element.yesyes
contextmenuThe event fires when the user right-clicks on the element to open the context menu.yesyes
dblclickThe event is fired when the user double-clicks on the element.yesyes
mousedownThe event fires when the user presses a mouse button on the element.yesyes
mouseenterThe event fires when the mouse pointer moves over the element.nono
mouseleaveThe event fires when the mouse pointer moves out of the element.nono
mousemoveThe event is fired when the mouse pointer is moving while on the element.yesyes
mouseoverThe event fires when the mouse pointer moves over the element.yesyes
mouseouthe event fires when the mouse pointer moves out of the element.yesyes
mouseupThe event is fired when the user releases the mouse button on the element.yesyes
wheelThe event is fired when the mouse wheel rotates up and down on the element.

Keyboard event

EventDescriptionBubblesCancelable
keydownThe event fires when any key on the keyboard is pressed.yesyes
keypressThe event fires when a key other than “Shift”, “Fn” and “Caps Lock” on the keyboard is pressed.yesyes
keyupThe event fires when a key on the keyboard is released from being pressed.yesyes