Javascript DOM HTML Element addEventListener() Method add different type event handlers

Introduction

You can add events of different types to the same element.

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

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

This example uses the addEventListener() method to add many events on the same button.

View in separate window

<!DOCTYPE html>
<html>
<body>
<button id="myBtn">Test</button>
<p id="demo"></p>

<script>
var x = document.getElementById("myBtn");
x.addEventListener("mouseover", myFunction);
x.addEventListener("click", mySecondFunction);
x.addEventListener("mouseout", myThirdFunction);

function myFunction() {/*  ww  w. java 2s  .  c  om*/
  document.getElementById("demo").innerHTML += "Moused over!<br>"
}

function mySecondFunction() {
  document.getElementById("demo").innerHTML += "Clicked!<br>"
}

function myThirdFunction() {
  document.getElementById("demo").innerHTML += "Moused out!<br>"
}
</script>

</body>
</html>



PreviousNext

Related