Browser Default Actions in JavaScript

Browser Default Actions in JavaScript

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

ActionDefault 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

document.querySelector("a").addEventListener("click", function(event) { event.preventDefault(); // Prevents navigation alert("Link clicked, but not navigating!"); });

šŸ›  Effect: Clicking the link will not take the user to a new page.

Example 2: Prevent Form Submission

document.querySelector("form").addEventListener("submit", function(event) { event.preventDefault(); // Stops form submission alert("Form submission prevented!"); });

šŸ›  Effect: The form won’t submit, preventing the page from reloading.

Example 3: Disable Right-Click

document.addEventListener("contextmenu", function(event) { event.preventDefault(); // Blocks the right-click menu alert("Right-click is disabled!"); });

šŸ›  Effect: Users cannot open the right-click menu.

Example 4: Prevent Dragging an Image

document.querySelector("img").addEventListener("dragstart", function(event) { event.preventDefault(); // Stops image dragging alert("Dragging is disabled!"); });

šŸ›  Effect: Users cannot drag images.

šŸ”¹ Checking if preventDefault() is Allowed

Some browser actions cannot be prevented. We can check using event.defaultPrevented.

Example:

document.querySelector("a").addEventListener("click", function(event) { if (!event.defaultPrevented) { console.log("Default action will be prevented now."); event.preventDefault(); } });

šŸ”¹ 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!

Soeng Souy

Soeng Souy

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

Post a Comment

CAN FEEDBACK
close