The function
addEventListener
creates the specified event listener for the object.
In this case we add
click
event for the div element with id
div_element
without using anonymous function.
First we select the object that we want to create
click
event listener to
let div = document.getElementById('div_element');
Then we create the actual event listener for the event without anonymous function
div.addEventListener('click', func);
function func() {
alert('You clicked me!');
}
The same example using anonymous function
div.addEventListener('click', function(){
alert('You clicked me!');
})
HTML part of the examples:
<div id="div_element">Click Me</div>
Another method to add the event listener is to include
onclick
attribute inside opening tag
<div onclick="func()">Click Me</div>