HTML Events
In this page:
<tagname onevent="script">content</tagname>
What are HTML Events?
Events represent occurrences or actions that happen in the browser, typically triggered by user interactions. HTML allows you to bind event handlers directly to your tags to run JavaScript code when these actions occur.
Example: What are HTML Events?
<button onclick="alert('Clicked')">Click me</button>
Mouse Events
Mouse events trigger scripts in response to mouse interactions, such as clicking a button (onclick), double-clicking (ondblclick), or hovering over an element (onmouseover).
Example: Mouse Events
<button onclick="console.log('clicked')" ondblclick="console.log('double-clicked')" onmouseover="console.log('hovered')">
Hover or click me
</button>
Keyboard Events
Keyboard events trigger scripts in response to keyboard interactions, such as pressing a key down (onkeydown) or releasing it (onkeyup), which is useful for creating keyboard shortcuts.
Example: Keyboard Events
<input type="text" onkeydown="console.log('key down')" onkeyup="console.log('key up')">
Form Events
Form events trigger scripts in response to form interactions, such as submitting a form (onsubmit), changing an input value (onchange), or typing inside a text field (oninput).
Example: Form Events
<form onsubmit="event.preventDefault()">
<input type="text" onchange="console.log('changed')" oninput="console.log('typing')">
</form>
Window Events
Window events trigger scripts in response to browser window actions, such as when the page finishes loading (onload), when the window is resized (onresize), or when the user scrolls (onscroll).
Example: Window Events
<body onload="console.log('page loaded')" onresize="console.log('resized')" onscroll="console.log('scrolled')">
</body>
- Writing complex, heavy JavaScript code directly inside inline HTML event attributes.
- Forgetting to call preventDefault on form submit events, causing the browser to reload the page.
- Binding heavy, unoptimized scripts to scroll and resize events, slowing down page performance.
- HTML events trigger JavaScript code in response to user or browser window actions.
- Use mouse events (like onclick) and keyboard events (like onkeyup) to handle user inputs.
- Use form events (like onsubmit) to validate data on the front-end, and window events (like onload) to initialize your scripts safely.
Standard HTML event triggers and attributes are supported natively by all web browsers.
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: