addEventListener – JavaScript Methods

The addEventListener() method is used to listen for a specific event, and handle that event when it occurs.

Syntaxobject.addEventListener( event, function, useCapture )

Tóm Tắt

Parameters

event
A string representing the event you wish to target without any ‘on’ prefix applied to it.

function
The function that stands ready to run when the event fires off.

useCapture (optional)
An optional boolean value that specifies whether or not you want all events of this type to be associated with the specified listener function before reaching other listeners beneath it in the document for that type of event. Default value is false if not specified.

Examples

Add a ‘load’ event listener to the window object.
function init(){
alert("document loaded");
}
window.addEventListener( "load", init, false );

Add a ‘click’ event to multiple elements that could be handled by the same function, or separate functions.
<button id="btn1">Click me 1</button>
<button id="btn2">Click me 2</button>
<button id="btn3">Click me 3</button>
<script>
function clickHandler(event){
alert( "you clicked " + event.target.id );
}
btn1.addEventListener( "click", clickHandler );
btn2.addEventListener( "click", clickHandler );
btn3.addEventListener( "click", clickHandler );
</script>