JS Events

By using JS, we have the ability to add dynamism in the web pages. Events are the actions that can be detected by JS code.

Every element on a web page has certain events which can trigger JS functions. For example, we can use the onclick event of a button element to indicate that a function will run when a user clicks on the button. We can define the events in the HTML tags.

Examples of events are:~

  • A mouse click
  • A web page or an image loading
  • Mousing over a hot spot on the web page
  • Selecting an input box in an HTML form
  • Submitting an HTML form
  • A keystroke

Basically, JS Events are normally used in combination with functions, and the function will not be executed before the event occurs.

HTML allows event handler attributes, with JS code, to be added to HTML elements (or tags).

Syntax:

<element event = "JS code">
 
 

Some of the well-known JS Events are listed below.

Here is a list of some well-known JS events:

Event

Description

onclick

The user clicks an HTML element

onchange

An HTML element has been changed

onload

The browser has finished loading the page

onsubmit

The user submits an HTML form

onmouseover

The user moves the mouse over an HTML element

onmouseout

The user moves the mouse away from an HTML element

onkeydown

The user pushes a keyboard key

 

The following codes show the examples of JS Events.

 
Example 1: Illustration of JS Events
<html>
<body>

<button onclick="document.getElementById('test').innerHTML = Date()">Show Date & Time</button>

<p id="test"></p>

</body>
</html>

Output:

On clicking the button we will get the following output.

Sun Nov 10 2019 23:57:03 GMT+0530 (India Standard Time)

 
Example 2: Illustration of JS Events
<html>
<body>

<input type="button" id="buttonClick" value="Click Me!"/>

<script>
document.getElementById("buttonClick").addEventListener("click", clickTest);
function clickTest() { alert("You clicked on me!"); } </script>
</body> </html>

Output:

By clicking the button, the output that is shown above will be produced.