Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

JavaScript event


May 06, 2021 JavaScript


Table of contents


JavaScript events

Events are behaviors that can be detected by JavaScript.


HTML events are things that happen on HTML elements.

JavaScript can trigger these events when using JavaScript on HTML pages.


HTML events

HTML events can be browser behavior or user behavior.

Each element in an HTML page can produce events that can trigger JavaScript functions.

Here's an example of an HTML event:

  • The HTML page is finished loading
  • When the HTML input field changes
  • The HTML button is clicked

Usually, you can do something when something happens.

JavaScript can execute some code when an event is triggered.

Event properties can be added to HTML elements, and HTML elements can be added using JavaScript code.

Single quotes:

< some-HTML-element some-event = ' some JavaScript ' >

Double quotes:

< some-HTML-element some-event = " some JavaScript " >

In the following example, the onclick property (with code) is added to the button element:

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

Try it out . . .

In the above example, the JavaScript code modifies the contents of the id"demo" element.

In the next instance, the code modifies the contents of its own element (using this .innerHTML):

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

Try it out . . .

JavaScript event JavaScript code is usually a few lines of code. It is more common to call through event properties:

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

Try it out . . .


Common HTML events

Here's a list of some common HTML events:

Event Describe
onchange HTML elements change
onclick The user clicks on the 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 presses the keyboard button
onload The browser has finished loading the page

More event list: JavaScript Reference Manual - HTML DOM Events.


What can JavaScript do?

Events can be used to process form validation, user input, user behavior, and browser actions:

  • The event is triggered when the page loads
  • The event is triggered when the page is closed
  • The user clicks the button to perform the action
  • Verify the legitimacy of user input
  • Wait a minute...

There are several ways to execute JavaScript event code:

  • HTML event properties can execute JavaScript code directly
  • HTML event properties can call JavaScript functions
  • You can specify your own event handler for HTML elements
  • You can prevent events from occurring.
  • Wait a minute...
JavaScript event You'll learn more about events and event handlers in the HTML DOM section.