JavaScript Events

JavaScript Events

In our browser, anything we do is with the HTML. This HTML part has some predefined events to handle user interactions. Following are some of the HTML events:

onchangeThis event is triggered when an HTML element has been changed
onclickThis event is triggered when a user clicks an HTML element
onmouseoverThis event is triggered when the user moves the mouse over an HTML element
onmouseoutThis event is triggered when the user moves the mouse away from an HTML element
onkeydownThis event is triggered when the user pushes a keyboard key
onloadThis event is triggered when the browser has finished loading the page


A JavaScript function can be assigned to handle these events. For that to happen, we need to do the following:

  1. Load our JavaScript in the HTML body section [We have done this part in JavaScript setup earlier].
  2. Add the event attribute to your HTML and assign it the JavaScript function that you want to call.
    <element event=’JavaScript function’>
  3. Write a function with the same name assigned to the HTML event attribute and your required code within the function.

To understand the HTML events better, we will create a simple program.


Create a Program to take two inputs and print their sum on click of a button.


<!DOCTYPE html>
<link href="styles/style.css" rel="stylesheet" type="text/css">
<script src="scripts/index.js"></script>
<h1 id="idH1"> Addition Program</h1>
<h2 id="idH2"> Enter Two Numbers and Click the Sum button </h2>
<label>Enter First Number</label>
<Input id="idinput1"/>
<label>Enter Second Number</label>
<Input id="idinput2"/>
<button onclick="onSum()">Sum</button>
<label>Result :</label>
<label id="idResult" ></label>

CSS Code

h1 {
  color: red;
  padding-left: 10px;

h2 {
  color: blue;
  padding-left: 10px;

JavaScript Code

function onSum(){
    var num1 = Number(document.getElementById("idinput1").value);
    var num2 = Number(document.getElementById("idinput2").value);
    document.getElementById("idResult").innerHTML = num1+num2;

Output Screen before clicking the button:

Output Screen before clicking the button

Output Screen after clicking the button:

Output Screen after clicking the button

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.