Browser Default Actions in JavaScript
Browsers have built-in behaviors for user interactions, such as following links, submitting forms, right-clicking, etc. JavaScript allows us to prevent these default actions when needed.
🔹 Common Browser Default Actions
| Action | Default Behavior |
|---|---|
Clicking a link (<a href="...") | Navigates to the URL |
Submitting a form (<form>) | Sends data and reloads the page |
Right-click (contextmenu) | Opens the browser menu |
Dragging an element (dragstart) | Moves the element |
Pressing a key (keydown, keypress) | Inserts text, scrolls, etc. |
🔹 Prevent Default Actions Using event.preventDefault()
The event.preventDefault() method stops the default browser behavior.
✔ Example 1: Prevent a Link from Navigating
🛠 Effect: Clicking the link will not take the user to a new page.
✔ Example 2: Prevent Form Submission
🛠 Effect: The form won’t submit, preventing the page from reloading.
✔ Example 3: Disable Right-Click
🛠 Effect: Users cannot open the right-click menu.
✔ Example 4: Prevent Dragging an Image
🛠 Effect: Users cannot drag images.
🔹 Checking if preventDefault() is Allowed
Some browser actions cannot be prevented. We can check using event.defaultPrevented.
✔ Example:
🔹 When to Use preventDefault()?
✅ Form validation before submission.
✅ Custom right-click menus in web apps.
✅ Disabling drag-and-drop on sensitive elements.
✅ Handling keyboard shortcuts without interfering with defaults.
🚀 Mastering event handling lets you fully control user interactions in your web applications!
