The addEventListener() method is an inbuilt function in javascript and it is used to attach an event handler to a particular element. You can add multiple event handlers to a particular element without overwriting the existing event handlers.
document.addEventListener(event, function, Capture)
The third parameter is optional to define.
Simpler code:
document.addEventListener("click", function(){
document.getElementById("demo").innerHTML = "Hello World";
});
JavaScript addEventListener() example
Simple example code click the given HTML button to see the effect.
<!DOCTYPE html>
<html>
<body>
<button id = "btn"> Click</button>
<script>
document.getElementById("btn").addEventListener("click", fun);
function fun() {
console.log("Hello addEventListener()")
}
</script>
</body>
</html>
Output:
You can add any event listeners to the document:
<body>
<p>Click anywhere in the document.</p>
<p id="demo"></p>
<script>
document.addEventListener("click", f1);
document.addEventListener("click", f2);
function f1() {
document.getElementById("demo").innerHTML += "First function"
}
function f2() {
document.getElementById("demo").innerHTML += "Second function"
}
</script>
</body>
Or add different types of events:
document.addEventListener("mouseover", myFunction);
document.addEventListener("click", OtherFunction);
document.addEventListener("mouseout", someOtherFunction);
Do comment if you have any doubts or suggestions on this JS event handler topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version