Best HTML Event Handling addEventListener Tutorial
Learn how to use the JavaScript addEventListener() method for an optimal way of adding user interactivity into your websites and web applications that apply JavaScript. It cleans up your HTML markup and may be the only way to attach events to elements in the future.
Modern Version
<script>
function addListeners(){
document.getElementById('mybtn').addEventListener("click", btn1func);
document.getElementById('mybtn2').addEventListener("mouseover", btn2func);
function btn1func(){
alert(this.id+" : mouse-click makes script run");
}
function btn2func(){
alert(this.id+" : mouse-over makes script run");
}
}
window.addEventListener("load", addListeners);
</script>
<button id="mybtn">Click Button</button>
<button id="mybtn2">Hover Event</button>
Older Version (supports versions of Internet Explorer previous to IE9)
<!DOCTYPE html>
<html>
<head>
<script>
function addListeners(){
if(window.addEventListener) {
document.getElementById('mybtn').addEventListener("click",btn1func,false);
document.getElementById('mybtn2').addEventListener("mouseover",btn2func,false);
} else if (window.attachEvent){ // Added For Inetenet Explorer versions previous to IE9
document.getElementById('mybtn').attachEvent("onclick", btn1func);
document.getElementById('mybtn2').attachEvent("onmouseover",btn2func);
}
// Write your functions here
function btn1func(){
alert(this.id+" : mouse-click makes script run");
}
function btn2func(){
alert(this.id+" : mouse-over makes script run");
}
}
window.onload = addListeners;
</script>
</head>
<body>
<button id="mybtn">Click Button</button>
<button id="mybtn2">Hover Event</button>
</body>
</html>