🖱️ Events: Mouse and Keyboard Events
The Magic Buttons of the Web
Imagine you have a magical toy box. Every time you touch it, poke it, or wave your hand over it, something amazing happens! Maybe it lights up, plays music, or opens a secret door.
That’s exactly how websites work!
When you click a button, move your mouse, or press a key on your keyboard, the website is listening and waiting to do something cool. These are called Events.
🎯 What Are Events?
Think of events like signals or messages.
- You do something (click, move, type)
- The website hears it
- The website responds
It’s like having a conversation with your computer!
You: *clicks button*
Website: "I heard that! Let me show you something!"
🖱️ Click Events
The Most Powerful Touch
A click is like tapping something with your finger. It’s the most common way we talk to websites.
The click Event
When you press and release your mouse button on something:
const button = document.getElementById('myButton');
button.addEventListener('click', function() {
console.log('You clicked me!');
});
Real Life Example: Clicking the “Play” button on a video.
The dblclick Event
Double-click means clicking twice really fast!
button.addEventListener('dblclick', function() {
console.log('Double click detected!');
});
Real Life Example: Double-clicking to zoom into a photo.
Mouse Button Types: mousedown and mouseup
mousedown= The moment you press the button downmouseup= The moment you let go
button.addEventListener('mousedown', function() {
console.log('Button pressed down!');
});
button.addEventListener('mouseup', function() {
console.log('Button released!');
});
Think of it like this:
mousedown= Your finger touches the piano keymouseup= Your finger lifts off the keyclick= Both together!
graph TD A["You press mouse button"] --> B["mousedown fires"] B --> C["You release mouse button"] C --> D["mouseup fires"] D --> E["click fires"]
🏃 Mouse Movement Events
Following Your Every Move
The website can track your mouse like a cat watching a laser pointer!
The mousemove Event
This fires constantly as you move your mouse:
document.addEventListener('mousemove', function(event) {
console.log('X:', event.clientX);
console.log('Y:', event.clientY);
});
Where is my mouse?
event.clientX= How far from the leftevent.clientY= How far from the top
Real Life Example:
- Drawing apps that follow your mouse
- Games where things follow your cursor
🚨 Be Careful!
mousemove fires hundreds of times per second! Don’t do heavy work inside it.
🚪 Mouse Enter and Leave
Coming and Going
Imagine a room with a motion sensor. It knows when you walk in and when you walk out.
The mouseenter Event
Fires when your mouse enters an element:
const box = document.getElementById('myBox');
box.addEventListener('mouseenter', function() {
console.log('Welcome! You entered the box!');
});
The mouseleave Event
Fires when your mouse leaves an element:
box.addEventListener('mouseleave', function() {
console.log('Goodbye! You left the box!');
});
The mouseover and mouseout Family
These are similar but work slightly different:
| Event | Fires When |
|---|---|
mouseenter |
Mouse enters element (doesn’t bubble) |
mouseleave |
Mouse leaves element (doesn’t bubble) |
mouseover |
Mouse enters element OR its children (bubbles) |
mouseout |
Mouse leaves element OR its children (bubbles) |
Simple Rule:
- Use
mouseenter/mouseleavefor most things - Use
mouseover/mouseoutwhen you need to know about children too
graph TD A["Mouse approaches box"] --> B["mouseenter fires once"] B --> C["Mouse hovers around inside"] C --> D["Mouse leaves box"] D --> E["mouseleave fires once"]
Real Life Examples:
- Menus that open when you hover
- Images that zoom when mouse is over them
- Tooltips that appear and disappear
⌨️ Keyboard Events
Your Keyboard is Talking!
Every time you press a key, your keyboard sends a message to the website.
The Three Keyboard Events
graph TD A["You start pressing key"] --> B["keydown fires"] B --> C["Key produces character"] C --> D["keypress fires - deprecated"] D --> E["You release key"] E --> F["keyup fires"]
keydown Event
Fires the moment you press a key down:
document.addEventListener('keydown', function(event) {
console.log('Key pressed:', event.key);
});
Important: If you hold a key down, keydown fires again and again!
keyup Event
Fires when you release the key:
document.addEventListener('keyup', function(event) {
console.log('Key released:', event.key);
});
Use keydown when: You want instant response (like games)
Use keyup when: You want to wait until they finish pressing
keypress Event ⚠️
Warning: This is old and deprecated! Don’t use it for new projects.
// ❌ Old way - don't use
document.addEventListener('keypress', function(event) {
console.log('Keypress:', event.key);
});
// ✅ New way - use keydown instead
document.addEventListener('keydown', function(event) {
console.log('Key:', event.key);
});
🔑 Key Properties
Understanding What Key Was Pressed
When a keyboard event happens, you get lots of information!
The event.key Property
This tells you which key was pressed as a readable name:
document.addEventListener('keydown', function(event) {
console.log(event.key);
// "a", "Enter", "ArrowUp", "Shift", etc.
});
Examples:
| You Press | event.key Shows |
|---|---|
| A key | "a" or "A" |
| Enter key | "Enter" |
| Space bar | " " |
| Arrow up | "ArrowUp" |
| Shift | "Shift" |
The event.code Property
This tells you the physical key on the keyboard:
document.addEventListener('keydown', function(event) {
console.log(event.code);
// "KeyA", "Enter", "Space", "ArrowUp"
});
Why two properties?
| Property | Description |
|---|---|
event.key |
What character it makes |
event.code |
Where the key is on keyboard |
Example: On a French keyboard, pressing what we call “A” might type a different letter, but event.code will still say "KeyA" because it’s in the same physical position.
Modifier Keys
These are special keys you hold while pressing others:
document.addEventListener('keydown', function(event) {
if (event.shiftKey) {
console.log('Shift is held!');
}
if (event.ctrlKey) {
console.log('Control is held!');
}
if (event.altKey) {
console.log('Alt is held!');
}
if (event.metaKey) {
console.log('Command/Windows is held!');
}
});
Detecting Key Combinations
Want to detect Ctrl + S? Here’s how:
document.addEventListener('keydown', function(event) {
if (event.ctrlKey && event.key === 's') {
event.preventDefault(); // Stop browser save
console.log('Custom save!');
}
});
The event.repeat Property
Tells you if the key is being held down:
document.addEventListener('keydown', function(event) {
if (event.repeat) {
console.log('Key is held down!');
} else {
console.log('First press!');
}
});
🎮 Putting It All Together
A Simple Example
Let’s make a box that responds to everything!
const box = document.getElementById('gameBox');
// Mouse clicks
box.addEventListener('click', () => {
box.style.background = 'blue';
});
// Mouse enter/leave
box.addEventListener('mouseenter', () => {
box.style.transform = 'scale(1.1)';
});
box.addEventListener('mouseleave', () => {
box.style.transform = 'scale(1)';
});
// Keyboard
document.addEventListener('keydown', (e) => {
if (e.key === 'ArrowUp') {
box.style.top =
parseInt(box.style.top) - 10 + 'px';
}
});
📝 Quick Summary
| Event | When It Fires |
|---|---|
click |
Mouse press + release |
dblclick |
Two quick clicks |
mousedown |
Mouse button pressed |
mouseup |
Mouse button released |
mousemove |
Mouse is moving |
mouseenter |
Mouse enters element |
mouseleave |
Mouse leaves element |
keydown |
Key is pressed |
keyup |
Key is released |
| Property | What It Tells You |
|---|---|
event.key |
The key name (“a”, “Enter”) |
event.code |
Physical key (“KeyA”) |
event.clientX/Y |
Mouse position |
event.shiftKey |
Is Shift held? |
event.ctrlKey |
Is Ctrl held? |
event.repeat |
Is key held down? |
🌟 You Did It!
Now you understand how websites listen to your mouse and keyboard! These events are the foundation of every interactive website, game, and app.
Remember:
- 🖱️ Mouse events = clicking, moving, hovering
- ⌨️ Keyboard events = pressing and releasing keys
- 🔑 Key properties = understanding exactly what was pressed
Go make something interactive! 🚀
