addEventListener method
The addEventListener method allows
you to assign event handlers to an element.
With it, you can specify, for example, what
to do when a button is clicked or what to
do when typing in a text field. In the first
parameter we specify the event type
to be passed, in the second - the function
that will be triggered after the event
specified in the first parameter. In the
third optional parameter, we pass the
features of the object
(once, capture, passive)
or the parameter useCapture.
Syntax
element.addEventListener('event type', function, [object features]);
or
element.addEventListener('event type', function, [useCapture]);
Example
Let's make it so that when a button is clicked, a message is displayed:
<input type="button" id="button" value="click me">
let button = document.querySelector('#button');
button.addEventListener('click', function() {
alert('message');
});
:
Example
Let's write code so that when focus is lost in an input, a message with the text of this input is displayed:
<input id="input" value="text">
let input = document.querySelector('#input');
input.addEventListener('blur', function() {
alert(this.value);
});
:
Example
Let's make it so that when a button is clicked, a message is displayed in the console only once. To do this, we use the second parameter:
<input type="button" id="button" value="click me">
let button = document.querySelector('#button');
button.addEventListener('click',
function() {
console.log('message');
},
{
once: true
}
);
Example
The parameter passive prevents the
event.preventDefault method from
being called when handling the event. Let's
apply the event.preventDefault method
to the previous example, and also set the
parameter passive to true:
<input type="button" id="button" value="click me">
let button = document.querySelector('#button');
button.addEventListener('click',
function(event) {
event.preventDefault();
console.log('No message');
},
{
passive: true
}
);
After executing the code, we will see the following messages:
'No message';
'Unable to preventDefault inside passive event listener invocation.'
Example
The parameter useCapture set to
true shows the bubbling up of events
from an inner element to an outer element,
with the value false - from the
outer element to the inner element. When
passing the parameter useCapture,
its name is omitted and simply true
or false is written. Let's see how
events bubble in the parent and child
elements when they are clicked:
<div id="parent">Parent
<p id="child">Child</p>
</div>
#parent{
width: 60px;
padding: 10px;
border: 1px solid red;
text-align: center;
}
#child{
width: 60px;
marging-right: 40px;
border: 1px solid blue;
text-align: center;
}
let parent = document.querySelector('#parent');
let child = document.querySelector('#parent');
parent.addEventListener('click',
() => alert('parent'),
true
);
child.addEventListener('click',
() => alert('child'),
true
);
:
See also
-
the
removeEventListenermethod
that unbinds an event from an element