HTML events are occurrences that affect HTML elements.
When JavaScript is incorporated into HTML pages, it can respond to these events.
An HTML event refers to actions triggered by the browser or user interaction, such as:
When events occur, specific actions are often needed.
JavaScript enables executing code in response to events, and HTML allows adding event handler attributes with JavaScript code to elements.
With single quotes:
<element event=’some JavaScript‘> |
With double quotes:
<element event=”some JavaScript“> |
In the following example, a <button> element is augmented with an onclick attribute containing JavaScript code.
Example
<button onclick=”document.getElementById(‘demo’).innerHTML = Date()”>The time is?</button> |
In the previous example, the JavaScript code updates the content of the element with id="demo"
.
In the next example, it changes the content of its own element using this.innerHTML
.
Example
<button onclick=”this.innerHTML = Date()”>The time is?</button> |
JavaScript code frequently extends across multiple lines. It’s more typical to encounter event attributes invoking functions. |
Example
<button onclick=”displayDate()”>The time is?</button> |