Advance JavaScript (DOM, BOM, Web API) / Document Object Model

Event Handling - User Interaction

๐Ÿ–ฑ๏ธ Mouse Events

Mouse events detect how users interact using the mouse.

๐Ÿ“Œ Why Mouse Events Matter

  • React to user intention

  • Build interactive UI

  • Improve UX (hover, drag, menus)

๐Ÿงฉ Common Mouse Events

Event

Fires When

click

Mouse button clicked

dblclick

Double click

mouseover

Cursor enters element

mouseout

Cursor leaves element

mouseenter

Cursor enters (no bubbling)

mouseleave

Cursor leaves (no bubbling)

mousemove

Mouse moves

๐Ÿง  How it Works

  • mouseover โ†’ cursor enters โ†’ color changes

  • mouseout โ†’ cursor leaves โ†’ color resets

๐Ÿ“Œ Real-World Uses

โœ” Hover effects

โœ” Tooltips

โœ” Dropdown menus

โœ” Drag & drop


โŒจ๏ธ Keyboard Events

Keyboard events track key presses and releases.

๐Ÿงฉ Common Keyboard Events

Event

Meaning

keydown

Key pressed

keyup

Key released

๐Ÿงช Detect Pressed Key Example

document.addEventListener("keydown", (event) => {
  console.log(event.key);
});
a
Enter
Escape

๐Ÿง  Important Properties

Property

Meaning

event.key

Actual key value

event.code

Physical key

event.ctrlKey

Ctrl pressed?

event.shiftKey

Shift pressed?

๐Ÿ“Œ Real-World Uses

โœ” Form validation

โœ” Keyboard shortcuts

โœ” Games

โœ” Accessibility


๐Ÿ“œ Scroll Events

Scroll events fire when the user scrolls the page or an element.

๐Ÿ“Œ Common Use Cases

โœ” Infinite scrolling

โœ” Sticky headers

โœ” Reveal animations

โœ” Scroll progress bars

โš ๏ธ Performance Warning

  • Fires many times per second

  • Heavy logic can cause lag

โœ” Use throttle or debounce in real apps


๐ŸŽฏ scrollIntoView()

Scrolls a specific element into the visible area.

๐Ÿง  Why Itโ€™s Useful

โœ” No manual scroll math

โœ” Cleaner code

โœ” Smooth UX

๐Ÿ“Œ Common Uses

โœ” Navigation links

โœ” โ€œScroll to sectionโ€ buttons

โœ” Help & FAQ navigation


๐ŸŽฏ Focus Events

Focus events detect when an element gains or loses focus.

Event

Meaning

focus

Element selected

blur

Element deselected

focusin

Elements focused in

focusout

Elemenrs Focused out

๐Ÿ“Œ Why Focus Events Matter

โœ” Form validation

โœ” Accessibility (keyboard users)

โœ” Better UX feedback


๐Ÿ”— hashchange Event

Triggered when the URL hash (#) changes.

๐ŸŒ Example URL

example.com/#profile
example.com/#settings

๐Ÿง  How It Works

  • Clicking anchor links changes hash

  • Page does not reload

  • hashchange event fires

๐Ÿ“Œ Real-World Uses

โœ” Single Page Applications (SPA)

โœ” Tab navigation

โœ” Section routing


๐Ÿง  Quick Summary

Event Type

Used For

Mouse

Hover, clicks

Keyboard

Shortcuts, forms

Scroll

Animations, loading

scrollIntoView

Smooth navigation

Focus

Form UX

hashchange

SPA routing