JavaScript HTML DOM Events


The HTML DOM enables JavaScript to respond to events in HTML.

Mouse Over Me
Click Me
Click Me Again

Reacting to Events

When something happens on a webpage, like a user clicking a button, a piece of JavaScript code can run to respond to that event.

To make code run when someone clicks on something, insert JavaScript code into an HTML event attribute.

onclick=JavaScript

Instances of HTML events:

  • When someone presses the mouse button.
  • When a webpage finishes loading
  • When a picture is loaded
  • When you move the mouse over something.
  • When you alter an input field.
  • When you send an HTML form.
  • When someone presses a key

In this instance, when a user clicks on the <h1> element, its content is modified.

In this instance, a function gets invoked through the event handler.


HTML Event Attributes

You can link actions to HTML elements by using event attributes.

In the example provided, a function called displayDate will run when the button is clicked.


Assign Events Using the HTML DOM

You can use JavaScript to assign events to HTML elements through the HTML DOM.

In the given example, a function called displayDate is linked to an HTML element identified by the id="myBtn".

The task is to perform the function when the button is pressed.


The onload and onunload Events

The page triggers events called onload and onunload when the user comes to or leaves the page.

The onload event helps determine the visitor's browser type and version. It allows loading the appropriate web page version according to this information.

You can use the onload and onunload events to manage cookies.


The oninput Event

The oninput event usually triggers an action when the user enters data.

Here's an example demonstrating how to use "oninput" to modify the content of an input field.


The onchange Event

The onchange event is commonly used when checking input fields for correctness.

Here's an example of using the onchange event. The upperCase() function gets triggered when a user modifies the content of an input field.


The onmouseover and onmouseout Events

The onmouseover and onmouseout events are used to activate a function when the user moves the mouse over or away from an HTML element.


The onmousedown, onmouseup and onclick Events

The mouse-click process involves three events: onmousedown, onmouseup, and onclick. Initially, the onmousedown event is activated when a mouse button is pressed. Subsequently, the onmouseup event is triggered upon releasing the mouse button. Finally, the onclick event is triggered to signify the completion of the mouse-click.