Learn how JavaScript listens for user interactions — mouse clicks, keyboard input, form submissions — and executes code in response to make pages truly interactive.
Event handling in JavaScript is the process of detecting user interactions — such as clicks, keystrokes, or form submissions — and executing specific code in response. The code that runs is called an event handler or event listener.
Events are the bridge between the user and your JavaScript logic. Without event handling, a web page is a static document. With it, every button press, every keystroke, and every form submission can trigger a response.
Events are actions the user performs — JavaScript listens for them and reacts:
event.preventDefault() to stop the page reload
<button onclick="handleClick()">Click Me</button>
<script>
function handleClick() {
console.log("Button was clicked!");
}
</script>
onclick is an inline event attribute — the simplest way to attach a handlerhandleClick() automatically<input type="text" onkeyup="handleKey(event)"
placeholder="Start typing...">
<script>
function handleKey(event) {
console.log("Key released:", event.key);
console.log("Current value:", event.target.value);
}
</script>
event object is passed automatically — it contains details about what happenedevent.key tells you which key was pressed ("Enter", "a", "Backspace" etc.)event.target is the element that triggered the event — here the input field<form onsubmit="handleSubmit(event)">
<input id="nameField" type="text" placeholder="Your name">
<button type="submit">Submit</button>
</form>
<p id="msg"></p>
<script>
function handleSubmit(event) {
event.preventDefault(); // stops the page from reloading
let name = document.getElementById("nameField").value;
document.getElementById("msg").textContent =
"Hello, " + name + "!";
}
</script>
event.preventDefault() stops thisevent parameter must be passed from the HTML attribute: onsubmit="handleSubmit(event)"<input id="search" type="text" oninput="liveSearch(this)"
placeholder="Type to search...">
<p id="result"></p>
<script>
let items = ["Apple", "Banana", "Mango", "Grapes", "Orange"];
function liveSearch(input) {
let query = input.value.toLowerCase();
let match = items.filter(i => i.toLowerCase().includes(query));
document.getElementById("result").textContent =
query ? "Found: " + match.join(", ") : "";
}
</script>
oninput fires on every character change — faster and more responsive than onkeyupthis refers to the element that fired the event — a shortcut to avoid getElementByIdThink of a doorbell system — the event model maps perfectly:
Click ▶ Preview to see all three event types — mouse, keyboard, and form — working together in a single page.
<!DOCTYPE html>
<html>
<head><title>Events Demo</title></head>
<body style="font-family:sans-serif;padding:24px;background:#f8f9fa">
<h2>Event Handling Demo</h2>
<!-- Mouse event -->
<button onclick="handleClick()"
style="padding:8px 18px;background:#f7df1e;border:none;border-radius:6px;
cursor:pointer;font-weight:700;font-size:1rem">
Click Me
</button>
<!-- Keyboard event -->
<input type="text" onkeyup="handleKey(event)"
placeholder="Type something..."
style="display:block;margin:12px 0;padding:8px 12px;
border:1px solid #ccc;border-radius:6px;font-size:1rem;width:240px">
<!-- Form event -->
<form onsubmit="handleSubmit(event)"
style="display:flex;gap:8px;align-items:center">
<input id="nameIn" type="text" placeholder="Enter name"
style="padding:8px 12px;border:1px solid #ccc;border-radius:6px;
font-size:1rem;width:180px">
<button type="submit"
style="padding:8px 18px;background:#4ade80;border:none;border-radius:6px;
cursor:pointer;font-weight:700;font-size:1rem">
Submit
</button>
</form>
<div id="log"
style="margin-top:16px;font-family:monospace;font-size:0.9rem;
background:#1e1e2e;color:#cdd6f4;border-radius:8px;padding:14px;
min-height:60px;line-height:2">
Waiting for events...
</div>
<script>
let logEl = document.getElementById("log");
function addLog(msg) {
logEl.innerHTML = msg + "<br>" + logEl.innerHTML;
}
function handleClick() {
addLog("🖱 Mouse: button clicked");
}
function handleKey(event) {
addLog("⌨ Key up: [" + event.key + "] value: "" + event.target.value + """);
}
function handleSubmit(event) {
event.preventDefault();
let name = document.getElementById("nameIn").value.trim();
addLog("📋 Form submitted: " + (name || "(empty)"));
}
</script>
</body>
</html>
<button onclick="greet()">Click Me</button>
<script>
function greet() {
// show alert "Welcome Aman"
}
</script>
greet() function to show "Welcome Aman"new Date().toLocaleTimeString()event.target.textContent<input type="text" oninput="logTyping(event)"
placeholder="Type here...">
<form onsubmit="submitForm(event)">
<input id="email" type="text" placeholder="Email">
<button type="submit">Submit</button>
</form>
logTyping(), print "Typing: [value]" using event.target.valuesubmitForm(), call event.preventDefault() first — then log the email<button onclick="console.log('clicked')">Go</button>
onclick handles mouse click events on any element. onhover and onpress do not exist in standard HTML. onchange fires when an input's value changes and focus is lost.
onkeydown fires the moment a key is pressed. onkeyup fires when it is released. oninput fires when the value actually changes — the most common choice for real-time text detection.
event.preventDefault() do on a form submission?
<form onsubmit="handle(event)">
<button type="submit">Submit</button>
</form>
<script>
function handle(e) {
e.preventDefault();
console.log("Handled in JS — no reload!");
}
</script>
event.preventDefault() cancels the browser's built-in default behaviour for that event. For forms, the default is to reload the page and send data to a server — calling this lets you handle the data entirely in JavaScript.
Know the difference between keydown, keyup, and input — each fires at a different moment:
<input id="demo" type="text" placeholder="Watch the console"
onkeydown="console.log('DOWN:', event.key)"
onkeyup="console.log('UP: ', event.key)"
oninput="console.log('INPUT value:', this.value)">
Prefer addEventListener() over inline onclick="" attributes — it keeps HTML and JavaScript separate and allows multiple handlers on the same element:
<button id="myBtn">Click me</button>
<script>
// Inline (avoid) → ties logic to HTML
// <button onclick="...">
// addEventListener (preferred) → separates concerns
document.getElementById("myBtn").addEventListener("click", function() {
console.log("Clicked via addEventListener!");
});
</script>
The event object gives you rich information about any event — always pass it to your handler when you need context:
// event.type — "click", "keyup", "submit"…
// event.target — the element that fired the event
// event.key — which key was pressed (keyboard events)
// event.clientX — mouse X position on screen (mouse events)
document.addEventListener("click", function(e) {
console.log("Type:", e.type);
console.log("Target:", e.target.tagName);
console.log("Position:", e.clientX, e.clientY);
});
Never forget event.preventDefault() on form submit handlers — without it the page reloads and your JavaScript never gets to process the data.
Will the page reload after the alert shows? Why or why not? Think before clicking Submit in the preview.
<form onsubmit="handleIt(event)">
<button type="submit">Submit</button>
</form>
<script>
function handleIt(event) {
event.preventDefault();
alert("Form submitted!");
}
</script>
// Step 1: User clicks the Submit button
// The browser fires the "submit" event on the form
// onsubmit calls handleIt(event)
// Step 2: event.preventDefault() is called FIRST
// This cancels the browser's default action:
// the page will NOT reload
// Step 3: alert("Form submitted!") runs
// The alert appears — and since the page did NOT reload,
// when the user clicks OK everything stays as it was
// Answer: NO — the page will NOT reload.
// event.preventDefault() stopped it.
// What if you removed event.preventDefault()?
// The page WOULD reload immediately after the alert
// because the browser resumes its default submit behaviour.
// Key rule:
// Default form behaviour → reload / navigate to action URL
// With event.preventDefault() → you handle everything in JS