An HTML Event is something that happens to an HTML element. When JavaScript is used in HTML pages, the browser can "react" to these events.
An event can be something the browser does or something a user does.
Events are signals that something has occurred. Here are some common examples:
You can execute JavaScript code when an event occurs by adding an event handler attribute to an HTML element.
The simplest way is to add the code directly to the HTML tag:
For better organization, it is recommended to call a function defined in a <script> tag:
function displayDate() {
document.getElementById("demo").innerHTML = Date();
}
<script>Here is a list of the most frequently used events that every web developer should know:
| Event | Description | Use Case |
|---|---|---|
| onclick | The user clicks an HTML element. | Buttons, links, and navigation menus. |
| onchange | An HTML element has been changed. | Validating text in an input field. |
| onmouseover | The user moves the mouse over an element. | Showing tooltips or changing colors. |
| onmouseout | The user moves the mouse away from an element. | Resetting styles after a hover. |
| onkeydown | The user pushes a keyboard key. | Creating shortcuts or character limits. |
| onload | The browser has finished loading the page. | Initializing scripts or animations. |
Events allow your website to be interactive. Without events, a website is just a static document. With events, you can:
While inline attributes like onclick are easy, modern developers prefer using addEventListener(). This keeps your HTML clean and allows you to add multiple events to a single element.
const myButton = document.getElementById("myBtn");
myButton.addEventListener("click", function() {
alert("Hello World!");
});
Identify the Trigger: Decide what action the user should take (click, hover, type).
Define the Action: Write the JavaScript function that should run.
Connect Them: Link the event to the element using an attribute or a listener.