Curriculum
Course: JavaScript Basic
Login

Curriculum

JavaScript Basic

JSHome

0/216
Text lesson

DOM Events

The HTML DOM enables JavaScript to respond to HTML events.

Reacting to Events

JavaScript can be triggered when an event occurs, such as when a user clicks on an HTML element.

To run code when a user clicks on an element, you can add JavaScript to the HTML event attribute.

onclick=JavaScript

Examples of HTML events include:

  • When a user clicks the mouse
  • When a web page finishes loading
  • When an image is loaded
  • When the mouse moves over an element
  • When an input field value is changed
  • When an HTML form is submitted
  • When a user presses a key

In this example, the content of the <h1> element changes when the user clicks on it:

Example

<!DOCTYPE html>
<html>
<body>

<h1 onclick=”this.innerHTML = ‘Ooops!'”>Click on this text!</h1>

</body>
</html>

In this example, a function is invoked through the event handler.

Example

<!DOCTYPE html>
<html>
<body>

<h1 onclick=”changeText(this)”>Click on this text!</h1>

<script>
function changeText(id) {
  id.innerHTML = “Ooops!”;
}
</script>

</body>
</html>