JavaScript DOM Event Handling
DOM - Event Handling
Event Handling :
We earlier talked about event handlers in JavaScript which are invoked using inline scripting. This approach has a limitation of tight coupling of the script code with the HTML element.
DOM API, provides us couple of more ways to handle events in JavaScript using internal or external scripting. It segregates HTML elements completely from any JavaScript code. There are 2 different ways of doing this.
Consider that you want to listen to the click event on the para elements, given are two different ways of doing it.
Example:
Demo :
CODE/PROGRAM/EXAMPLE
//HTML code
<html>
<head>
</head>
<body>
<h2>Event Handling</h2>
<p id="para1">Para one of my page</p>
<p id="para2">Para two of my page</p>
</body>
</html>
CODE/PROGRAM/EXAMPLE
//JS code
document.getElementById("para1").onclick = function() {
alert("Para one just handled the event click");
};