Javascript DOM HTML Element addEventListener() Method add two handlers

Introduction

You can add many events to the same element, without overwriting existing events.

This example demonstrates how to add two click events on the same <button> element:

document.getElementById("myBtn").addEventListener("click", myFunction); document.getElementById("myBtn").addEventListener("click", someOtherFunction);

View in separate window

<!DOCTYPE html>
<html>
<body>

<p>This example uses the addEventListener() method to add two click events to the same button.</p>

<button id="myBtn">Test</button>

<script>
var x = document.getElementById("myBtn");
x.addEventListener("click", myFunction);
x.addEventListener("click", someOtherFunction);

function myFunction() {//from  w w w  . ja  v  a  2  s  .  co  m
  alert ("Hello World!")
}

function someOtherFunction() {
  alert ("This function was also executed!")
}
</script>

</body>
</html>



PreviousNext

Related