Understand where the event object comes from, what it contains, and how it works in real-time.
In JavaScript, every time something happens on a webpage — like a click, keypress, or form submit — the browser automatically creates an Event Object. This object stores all details about that event, such as:
target)type)clientX, clientY)timeStamp)You don’t create this object yourself — the browser provides it automatically and passes it to your event handler.
<button id="btn">Click Me</button>
<script>
const btn = document.getElementById("btn");
btn.addEventListener("click", function(event) {
console.log(event.type); // "click"
console.log(event.target); // <button id="btn">
console.log(event.clientX); // Mouse X position
});
</script>
When you type inside the input box, the browser creates a KeyboardEvent and provides details like which key was pressed.
<input type="text" id="keyInput" placeholder="Type here...">
<script>
document.getElementById("keyInput").addEventListener("keydown", function(e) {
console.log("Key:", e.key);
console.log("Code:", e.code);
});
</script>
The Event Object originates from the browser’s DOM event system. Every time you interact with the page:
EventTarget interface creates an event object (like MouseEvent).In short, the event object is born inside the browser, not JavaScript itself.
Different events produce different types of event objects:
| Event Type | Object Type | Example Properties |
|---|---|---|
| Click / Mouse Move | MouseEvent | clientX, clientY, button |
| Key Press | KeyboardEvent | key, code, ctrlKey |
| Form Submit | SubmitEvent | target, type |
| Scroll / Resize | UIEvent | view, detail |
| Custom Events | CustomEvent | detail |
event.preventDefault()
You can use event.preventDefault() to stop the browser's default action —
like preventing a form from submitting or a link from navigating.
<form id="demoForm">
<input type="text" placeholder="Enter name">
<button type="submit">Submit</button>
</form>
<script>
document.getElementById("demoForm").addEventListener("submit", function(event) {
event.preventDefault(); // stop form reload
alert("Form submission stopped by event.preventDefault()");
});
</script>