DEV Community

Sampson Ovuoba for Devwares

Posted on • Originally published at devwares.com on

Tutorial: Javascript Events

JavaScript Events

The "things" that happen to HTML components are known as HTML events. JavaScript can "respond" to these events when it is used in HTML pages.

HTML Events An HTML event can be initiated by the browser or initiated by the user. Here are some HTML event examples:

  • The loading of an HTML web page is complete.
  • A HTML input area has been modified.
  • An HTML button has been pressed.

When circumstances occur, you may feel compelled to act. When events are identified, JavaScript allows you to run code. HTML permits event handler attributes to be added to HTML elements using JavaScript code.

JavaScript Code:

<button onclick="document.getElementById('demo').innerHTML = Date()">The time is?</button>

Enter fullscreen mode Exit fullscreen mode

An onclick property is applied to a <button> element in the following example (with code). The content of the element with id="demo" is likewise changed by the JavaScript code.

The following code (using this.innerHTML) modifies the content of its own element:

JavaScript Code:

<button onclick="this.innerHTML = Date()">The time is?</button>

Enter fullscreen mode Exit fullscreen mode

The code in JavaScript is frequently many lines long. The following are examples of event characteristics that call functions:

JavaScript Code:

<button onclick="displayDate()">The time is?</button>.

Enter fullscreen mode Exit fullscreen mode

Common HTML Events

Here's a rundown of some of the most commonly occurring HTML events:

Event Description
onchange An HTML element has been changed
----------- ---------------
onclick The user clicks an HTML element
----------- ---------------
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
----------- ---------------
onload The browser has finished loading the page

What can JavaScript Do?

User input, user actions, and browser activities can all be handled and verified by event handlers:

  • Things that should be done when a website loads
  • Things that should be done when a page is closed
  • Actions that should be performed when a user clicks a button
  • Content that should be verified when a user enters data
  • And more...

There are several methods for allowing JavaScript to work with events:

  • HTML event attributes can call JavaScript functions
  • HTML event properties can run JavaScript code directly.
  • You can add your own event handler functions to HTML elements
  • You can stop events from being sent or handled
  • And much more...

The HTML DOM chapters cover a lot more information about events and event handlers.

Contrast Bootstrap UI Kit

Resources

You may find the following resources useful:

Discussion (0)