JavaScript Web development

JavaScript Events

JavaScript’s interaction with HTML is handled through events that occur when the user or the browser manipulates a page. When the page loads, it is called an event

HTML events are “things” that happen to HTML elements. When JavaScript is used in HTML pages, JavaScript can “react” on these events.

HTML Events

An HTML event can be something the browser does, or something a user does.

Here are some examples of HTML events:

  1. An HTML web page has finished loading
  2. An HTML input field was changed
  3. An HTML button was clicked

HTML allows event handler attributes, with JavaScript code, to be added to HTML elements.

<element event="some JavaScript">

In the following example, an onclick attribute (with code), is added to a <button> element:

<!DOCTYPE html>

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

<p id="demo"></p>



In the example above, the JavaScript code changes the content of the element with id=”demo”.

In the next example, the code changes the content of its own element (using this.innerHTML):

<!DOCTYPE html>

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



Common HTML Events

onchangeAn HTML element has been changed
onclickThe user clicks an HTML element
onmouseoverThe user moves the mouse over an HTML element
onmouseoutThe user moves the mouse away from an HTML element
onkeydownThe user pushes a keyboard key
onloadThe browser has finished loading the page

Enjoy coding!