Javascript DOM HTML Element addEventListener() Method with attachEvent() method

Introduction

For browsers that don't support the addEventListener() method, you can use the attachEvent() method.

This example demonstrates a cross-browser solution:

The addEventListener() method is not supported Internet Explorer 8 and earlier versions.

This example demonstrates a solution that will work for all browsers.

View in separate window

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

<script>
var x = document.getElementById("myBtn");
if (x.addEventListener) {/* w  ww .ja v  a  2 s. c  om*/
  x.addEventListener("click", myFunction);
} else if (x.attachEvent) {
  x.attachEvent("onclick", myFunction);
}

function myFunction() {
  
document.getElementById("demo").innerHTML = "Hello World!";
}
</script>

</body>
</html>



PreviousNext

Related