Categories
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

JavaScript Events

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>
<html>
<body>

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

<p id="example"></p>

</body>
</html>

Output:

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

<!DOCTYPE html>
<html>
<body>

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

</body>
</html>

Output:

Common HTML Events

EventDescription
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!

Hey, here’s something that might interest you:

JavaScript Loops

JavaScript Objects

JavaScript Toggle Class