JS Events

JS Tutorial

JS Version

JS Objects

JS Function

JS Classes

JS Async

JS HTML DOM

JS Browser BOM

JS Web API

JS AJAX

JS JSON

JS vs JQUERY

JS Graphics

JavaScript Events

HTML events are “things” that occur in HTML elements.

When JavaScript is embedded in HTML pages, JavaScript can “react” on these events.

HTML Events

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

Here are some examples of HTML events:

  • An HTML web page has finished loading.
  • An HTML input field was changed.
  • An HTML button was clicked.

JavaScript enables the user to execute code when events are detected.

HTML enables event handler attributes, with JavaScript code, that are added to HTML elements.

With single quotes:

<element event=’some JavaScript’>

With double quotes:

<element event=”some JavaScript”>

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

Example

<!DOCTYPE html>

<html>

<body>

<button onclick=”document.getElementById(‘demo’).innerHTML=Date()”>The time is?</button>

<p id=”demo”></p>

</body>

</html

Output

 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):

Example

<!DOCTYPE html>

<html>

<body

<h2>JavaScript HTML Events</h2>

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

</body>

</html>

Output

JavaScript HTML Events

JavaScript code is often several lines long.

It is more common to see event attributes calling functions.

<!DOCTYPE html>

<html>

<body>

<h2>JavaScript HTML Events</h2>

<p>Click the button to display the date.</p>

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

<script>

function displayDate() {

 document.getElementById(“demo”).innerHTML = Date();

}

</script>

<p id=”demo”></p>

</body>

</html>

Output

JavaScript HTML Events

Click the button to display the date.

JavaScript Event Handlers

Event handlers are used to handle and verify user input, user actions, and browser actions:

  • Things that must be done every time a page loads.
  • Things that must be done when the page is closed.
  • Action that must be performed when a button is clicked by the user.
  • Content that must be verified when a user inputs data.

Several different methods can be used to allow the working of JavaScript with events:

  • JavaScript code can be executed  directly by HTML event attributes.
  • JavaScript functions can be called by HTML event attributes.
  • You can assign your own event handler functions to HTML elements.
  • You can avoid events from being sent or being handled.