Event handlers in HTML Elements

An event handler is a predefined JavaScript property of an object that is used to handle an event on a web page.
When a viewer of a web page performs an action such as clicking a button, moving the mouse over a particular part of the web page etc means that an event is taking place. JavaScript can identify these events and react to them making the web page more interactive and useful.

Event handlers can can be place within HTML elements as attributes or they can be placed between <script> and </script> tags or in an external JavaScript file.

To use an event handler within an HTML document you need to know the keyword for that event handler.

Example:


<body>
   <form>
     <input type="button" value="Click Here" onclick="window.alert(Hi there!);" />
   </form>
</body>

When a user clicks the button an alert pops up that says “Hi there!”.
However, if the code within the event handler becomes very long then you can place it in a function. You can use the event handler to call the function.

Example:


<body>
   <script>
     function MyFunction() {
       window.alert("Hi");
     }
   </script>
   <form>
     <input type="button" value="Click Here" onclick="MyFunction();" />
   </form>
</body>

You can access the HTML element using the document.getElementById(); method. For this, first you have to assign an id to the HTML element.


<body>
   <form>
     <input type="button" value="Click Here" id="MyButton" />
   </form>
</body>

To access the HTML element with the id=”MyButton” you simply use the following code:


document.getElementById("MyButton");

Probably you would want to assign this expression to a variable so you can use it multiple times without re-typing it.


var HiMyButton = document.getElementById("MyButton");

The final script will look like this:


<script>
function MyFunction() {
   window.alert("Hi");
}
var HiMyButton = document.getElementById("MyButton");
MyButton.onclick = MyFunction;
</script>

On the last line of code MyButton.onclick = MyFunction; the parentheses are not used after the function name. That is because you want to assign the execution of the function not its result.

Leave a Reply