JavaScript DOM events are actions or occurrences that happen in the browser, such as mouse clicks, keyboard presses, form submissions, page loads, and more. JavaScript lets you listen to these events and run functions in response, making your web pages interactive and dynamic.
onclick directly in HTML tags.You can attach events directly in HTML using attributes like onclick, onmouseover, onsubmit, etc. This is simple but can become hard to manage in large projects.
Another way is to select an element in JavaScript and assign a function to a property like element.onclick or element.onmouseover. Each property can hold only one handler.
The preferred modern way is element.addEventListener(eventType, handler, useCapture). It allows multiple handlers for the same event and can control whether the handler runs in capturing or bubbling phase.
The onclick event is triggered when a user clicks an element. Here a button updates the text of a paragraph.
// Button that triggers the showMessage() function when clicked
<button onclick="showMessage()">Click Me</button>
// Empty paragraph where the message will be displayed
<p id="demo"></p>
// Script block containing the event handler function
<script>
function showMessage() {
// Find the paragraph and change its text when the button is clicked
document.getElementById("demo").innerText = "Button clicked!";
}
</script>
With addEventListener(), you can attach several handlers to the same event on one element without overwriting existing listeners.
// Button that will have multiple click handlers attached
<button id="multiBtn">Multi Handler</button>
// Script that demonstrates multiple event listeners on the same button
<script>
const btn = document.getElementById("multiBtn");
// First click handler: shows an alert
btn.addEventListener("click", function() {
alert("Handler 1 triggered!");
});
// Second click handler: logs a message to the console
btn.addEventListener("click", function() {
console.log("Handler 2 also triggered!");
});
</script>
Mouse events include clicks, hovering, entering, leaving, and pressing/releasing mouse buttons. Below, a box changes color when the mouse enters and leaves.
onclick – mouse clicks an elementonmouseover – mouse pointer enters an elementonmouseout – mouse pointer leaves an elementonmousedown / onmouseup – mouse button pressed / released
// A simple square div that will react to mouse hover
<div id="hoverBox" style="width:100px;height:100px;background:red;"></div>
// Script to change the color of the box on mouse events
<script>
const hoverBox = document.getElementById("hoverBox");
// When the mouse enters the box, change the background to blue
hoverBox.onmouseover = () => {
hoverBox.style.background = "blue";
};
// When the mouse leaves the box, change the background back to red
hoverBox.onmouseout = () => {
hoverBox.style.background = "red";
};
</script>
Keyboard events such as keydown, keyup, and keypress help detect which key the user is pressing.
// Text input that calls detectKey(event) on every keydown
<input
type="text"
id="textInput"
onkeydown="detectKey(event)"
placeholder="Type something"
/>
// Script that logs which key the user pressed
<script>
function detectKey(event) {
// event.key contains the character or key name that was pressed
console.log("Key pressed:", event.key);
}
</script>
The onsubmit event is commonly used to validate forms before sending data to the server. Returning false (or using event.preventDefault()) stops the form from submitting.
// Simple form that calls validateForm() when submitted
<form onsubmit="return validateForm()">
// Text input where the user must enter a name
<input type="text" id="name" placeholder="Enter name">
// Submit button to send the form
<input type="submit" value="Submit">
</form>
// Script to validate the form before allowing submission
<script>
function validateForm() {
const name = document.getElementById("name").value;
// If the name field is empty, show an alert and stop the form submission
if (name === "") {
alert("Name is required!");
return false; // stop submission
}
}
</script>
The onload event ensures that your script runs only after the entire page (including images and other resources) has finished loading.
// Script that waits for the window to finish loading
<script>
window.onload = function() {
// This code runs only after all page resources are fully loaded
console.log("The page has fully loaded.");
};
</script>
Every event handler receives an event object that holds useful information such as the event type, target element, and more.
// Button that passes the event object to the handler
<button onclick="handleEvent(event)">Event Info</button>
// Script that shows information from the event object
<script>
function handleEvent(e) {
// e.type is the event type, e.target is the element that triggered the event
alert(
"Type: " + e.type +
"\nTarget: " + e.target.tagName
);
}
</script>
Events in the DOM go through two main phases: capturing (from the window down to the target) and bubbling (from the target back up to the window).
In the example below, clicking the button will trigger the button's handler first, then the surrounding div's handler (bubbling).
// Outer div with a click handler
<div
onclick="alert('DIV clicked')"
style="padding:30px;background:#ddd;"
>
// Inner button with its own click handler
<button onclick="alert('BUTTON clicked')">Click</button>
</div>
Try this mini demo: click the button to change the message and type in the input to see which key you press.
Waiting for a click...
Key info will appear here.
When you click the demo button, a click event is fired on that button. The attached event handler updates the paragraph text to show that the button was clicked.
When you type in the input, each key press triggers a keydown event. The handler reads event.key to identify which key you pressed and displays it on the screen.
This is exactly how real web pages react to user actions: they listen for DOM events and modify the page or perform logic in response.
addEventListener() over inline onclick for flexibility and cleaner HTML.event.preventDefault() to stop default actions (like form submission or link navigation) when needed.event.target to know exactly which element triggered the event.window.onload or DOMContentLoaded so the DOM is ready.onclick.addEventListener to assign multiple actions to one element.mouseover and mouseout to animate color changes.type and target on a click.