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).


<element event = "JS code">

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

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




The user clicks an HTML element


An HTML element has been changed


The browser has finished loading the page


The user submits an HTML form


The user moves the mouse over an HTML element


The user moves the mouse away from an HTML element


The user pushes a keyboard key


The following codes show the examples of JS Events.

Example 1: Illustration of JS Events

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

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



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

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

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


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