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:

EventDescription
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.
    Syntax:
    <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.

Example

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

HTML Code

<!DOCTYPE html>
<html>
<head>
<link href="styles/style.css" rel="stylesheet" type="text/css">
<script src="scripts/index.js"></script>
</head>
<body>
<div>
<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"/>
<BR/>
<BR/>
<label>Enter Second Number</label>
<Input id="idinput2"/>
<BR/>
<BR/>
<button onclick="onSum()">Sum</button>
<BR/>
<BR/>
<label>Result :</label>
<label id="idResult" ></label>
</div>
</body>
</html>

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.