JavaScript Events
Events make web pages interactive. JavaScript can listen for clicks, key presses, mouse movements, form submissions, and many more actions — and respond instantly.
What is a JavaScript Event?
An event is anything that happens on a web page — a click, a key press, a form submit, a mouse move, the page loading. JavaScript can listen to these events and run code in response, making the page dynamic.
Common Event Types
Mouse
click, dblclick, mouseover, mouseout, mousemove.
Keyboard
keydown, keyup, keypress.
Form
submit, change, input, focus, blur.
Window
load, resize, scroll, beforeunload.
Touch
touchstart, touchend, touchmove (mobile).
Network
online, offline, fetch progress.
Three Ways to Attach Events
- HTML attribute:
<button onclick="go()"> - Property:
el.onclick = fn; - addEventListener:
el.addEventListener('click', fn)— recommended. - Use
removeEventListenerto detach when no longer needed.
Events in JavaScript
Events in JavaScript are actions or activities that occur in the browser. Events help developers create interactive and dynamic web applications.
Events can be triggered by clicking buttons, pressing keys, moving the mouse, submitting forms, loading pages, and more.
What is an Event ?
An event is a browser action detected by JavaScript. Using events, developers can execute specific code whenever a user performs an action.
Syntax
element.addEventListener(
'event',
function(e){
// e is event object
}
);
Your First Event
<button id="b">
Click Me
</button>
<p id="o"></p>
<script>
document
.getElementById('b')
.addEventListener(
'click',
() => {
document
.getElementById('o')
.innerText =
'Button Clicked!';
});
</script>
Examples
<body onmousedown="Key(event)">
<p>
PBA INSTITUTE
</p>
<script>
function Key(event){
if(event.altKey){
alert(
"ALT Key Pressed!"
);
}
else{
alert(
"ALT Key NOT Pressed!"
);
}
}
</script>
<body
onmousedown=
"KeyPressed(event)"
>
<p>
PBA INSTITUTE
</p>
<script>
function KeyPressed(event){
if(event.ctrlKey){
alert(
"CTRL Key Pressed!"
);
}
else{
alert(
"CTRL Key NOT Pressed!"
);
}
}
</script>
<div id="box" style=" width:120px; height:80px; background:#ddd" ></div> <script> let box = document .getElementById( 'box' ); box.onmouseover = () => box.style.background = 'orange'; box.onmouseout = () => box.style.background = '#ddd'; </script>
<div
onmousemove=
"Coords(event)"
style="
width:100px;
height:100px;
border:3px solid black"
></div>
<p id="pba"></p>
<script>
function Coords(event){
var x =
event.clientX;
var y =
event.clientY;
var coor =
"X : " + x +
" Y : " + y;
document
.getElementById(
"pba"
).innerHTML =
coor;
}
</script>
<input id="i">
<p id="o"></p>
<script>
document
.getElementById('i')
.addEventListener(
'keyup',
e => {
document
.getElementById('o')
.innerText =
'You typed: '
+ e.target.value;
});
</script>
<p
onmouseover=
"get(event)"
>
PBA INSTITUTE
</p>
<script>
function get(event){
alert(
event
.relatedTarget
.tagName
);
}
</script>
<form id="f">
<input
name="name"
id="n"
>
<button>
Submit
</button>
</form>
<script>
document
.getElementById('f')
.addEventListener(
'submit',
e => {
e.preventDefault();
alert(
'Hello '
+
document
.getElementById('n')
.value
);
});
</script>
<script>
window
.addEventListener(
'load',
() => {
document.write(
'Page fully loaded!'
);
});
</script>
<button id="b1">
Double Click
</button>
<script>
document
.getElementById('b1')
.ondblclick =
() =>
alert('Double!');
document
.addEventListener(
'contextmenu',
e => {
e.preventDefault();
console.log(
'Right click blocked'
);
});
</script>
Importance of Events
- Events create interactive websites.
- Events help respond to user actions.
- Events improve user experience.
- Events are used in forms, games, and apps.
Conclusion
Understanding JavaScript events is essential for building responsive and interactive applications. Events help developers create dynamic user interfaces easily.
Important Notes
- Prefer
addEventListenerover inlineonclick. - Use
e.preventDefault()to stop default behaviour (form submit, link click). - Use
e.stopPropagation()to prevent the event from bubbling up. - Always remove listeners you no longer need to avoid memory leaks.
Real-Life Use Cases
Form Validation
Listen to input events for live error checks.
UI Animations
Hover and click effects on buttons.
Game Controls
Keydown for movement, click for actions.
Live Search
Send request on each keystroke.
Practice Questions
- Create a button that counts how many times it has been clicked.
- Build a key-press counter that shows which key was pressed.
- Make a form that validates email format on submit.
- Highlight a box only while the mouse is on it.
- Show / hide a message on a single button using a toggle.
Frequently Asked Questions
| Question | Answer |
|---|---|
| Q. What is the event object? | It carries information about the event — target, key, position, type, etc. |
| Q. What is event bubbling? | When an event on a child element also triggers handlers on its parents. |
| Q. How do I stop a form from submitting? | Call e.preventDefault() inside the submit handler. |
| Q. What is event delegation? | Attaching one listener to a parent that handles events for many children using e.target. |
| Q. Why use addEventListener? | It allows multiple listeners and doesn't overwrite previous ones. |
Conclusion
Events are the heartbeat of interactive web pages. By mastering addEventListener, the event object, and common event types, you can build engaging, responsive interfaces with confidence.
JavaScript All Chapters
Continue Learning
Previous
Go to Small Application Chapter