JavaScript Events

HTML events are "things" that happen to HTML elements. When JavaScript is used in HTML pages, JavaScript can "react" on these events. An HTML event can be something the browser does, or something a user does.

For example,

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

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

<button onclick="document.getElementById('demo').innerHTML = Date()">Click to get time</button>

In this example, the JavaScript code changes the content of the element with id="demo".

HTML Events

Some common HTML events are:

  1. onchange: An HTML element has been changed

  2. onclick: The user clicks an HTML element

  3. onmouseover: The user moves the mouse over an HTML element

  4. onmouseout: The user moves the mouse away from an HTML element

  5. onkeydown: The user pushes a keyboard key

  6. onload: The browser has finished loading the page

Detecting Visitor Information

JavaScript programming often requires browser detection - that is, the detection of which browser a visitor to a website is using. For several years, browser detection was accomplished largely by using the userAgent property of the navigator object. The userAgent property is available through the navigator object and shows information about the user’s browser. However, relying on the userAgent property is no longer recommended, because visitors can easily forge it.

A much better way to track what is and is not supported in the visitor’s browser is a technique known as feature testing.

Feature testing

Using feature testing, sometimes referred to as object detection, a JavaScript program attempts to detect whether the browser that is visiting the web page supports a given feature. The typeof operator is the primary mechanism used to implement feature testing. In general terms, you use the operator as follows:

if (typeof featureName != "undefined") {
// Do Something With That Feature

For example, to test for the existence of the getElementById() method,

if (typeof document.getElementById != "undefined") {
alert("getelembyid is supported");
} else {
alert("no getelembyid support");