HTML Events

HTML events are "things" that happen to HTML elements. When JavaScript is used in HTML pages, JavaScript can "react" on these events. In other words, HTML element can contain a set of events which can trigger JavaScript Code. An HTML event can be something the browser does, or something a user does. Here are some examples of HTML events:

Often, when events happen, you may want to do something. JavaScript lets you execute code when events are detected. HTML allows event handler attributes, with JavaScript code, to be added to HTML elements.

     Using single quotes: <HTML-element event='some JavaScript'>
     Using double quotes: <HTML-element event="some JavaScript">

In the following example, an onclick attribute (with code), is added to a button element and the JavaScript code changes the content of the element with id='demo':

HTML file: Displayed by browser:
<body>
<button onclick="getElementById('demo').innerHTML=Date()">The time is?</button>
<p id='demo'></p>
</body>

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

HTML file: Displayed by browser:
<body>
<button onclick="this.innerHTML=Date()">The time is?</button>
</body>

JavaScript code is often several lines long. It is more common to see event attributes calling functions:

HTML file: Displayed by browser:
<body>
<p>Click the button to display the date.</p>
<button onclick="displayDate()">The time is?</button>
<script>
function displayDate() {
    document.getElementById("newdemo").innerHTML = Date();
}
</script>
<p id="newdemo"></p>
</body>

Click the button to display the date.


BackTable of ContentsNext