Table of contents
1.
Introduction
2.
Prevent Browser Actions
3.
Passive Handler
3.1.
Where can it be used?
4.
Event.defaultPrevented 
5.
Frequently Asked Questions
5.1.
What is a default action?
5.2.
What does prevent default do?
5.3.
How can we access an object’s inbuilt methods?
5.4.
How do I stop click event propagation?
6.
Conclusion
Last Updated: Mar 27, 2024
Easy

Browser Default Actions

Author Amit Singh
0 upvote

Introduction

In this article, we will learn about default actions performed by browsers in response to different events. These actions are known as default actions. But, sometimes, programmers need to disable them to start some other actions.

There are many events for which actions are already defined which are as follows:

  • Clicking on a link - initiates the navigation to its URL
  • Clicking on the submit button on a submission form - initiates the submission of the details to the server.
  • Moving the mouse pointer over a text while pressing the mouse button - selects the text.

These are just few examples of browser default actions, there are many more which we can observe while using any browser. 

But sometimes, we don't want the browser to perform the default action; instead, we want it to perform some other action. Here JS plays a huge role to handle such events. 

Before, let us learn how to prevent the browser from taking default actions:   

Prevent Browser Actions

Following are the two ways to stop the browser from performing the default actions:

  1. The way that is mainly used to prevent the browser’s actions is through the event object. A method event.preventDefault() can be called using this object.
  2. If the handler is assigned using on<event> (not by addEventListener), then returning false also works the same.

 

Let’s see an example, where we will stop a link from navigating. The browser will not be able to perform its default actions:

<!DOCTYPE html>
<html>
 <head>
   <title>Title of the webpage</title>
 </head>
 <body>
   <a href="https://www.codingninjas.com/" onclick="return false">Click here</a>
   <?-- Or we can use try this –> 
   <a href="https://www.codingninjas.com/" onclick="event.preventDefault()">Click here</a>
 </body>
</html>

In this example, we can see the use of return false and event.preventDefault() to stop the navigation. 

Now, let us try to click on the anchor tag. 

Output
 

As we can see when we clicked on the text it doesn’t go to the provided URL.

If you want to see the difference, write return true or remove the event.preventDefault() from the above code snippet. 

Passive Handler

There is an optional passive: true option of addEventListener, which signals to the browser that the preventDefault() is not going to be called by the handler.

Where can it be used?

When the user moves their finger across the screen on mobile devices, this initiates events like touchmove. This movement causes scrolling by default, but the handler can prevent this using the preventDefault() method.

So in case any of these events occur, the browser first has to process all the handlers, and then if the preventDefault() method is not present, only then will it perform the scrolling. This complete process takes time which causes unnecessary delays in the User Interface. The passive: true options inform the browser that the handler will not postpone scrolling.

For several browsers like Chrome and Firefox, passive is true for touchmove and touchstart events by default.

Event.defaultPrevented 

This property can be true or false depending on the browser's default action. If the default action has been successfully prevented, the property is true and else false. Sometimes event.defaultPrevented is used to signal other event handlers about the handling of the event.

Let’s see an example: 

<!DOCTYPE html>

<html>
  <head>
    <title>Title of the Page</title>
  </head>
  <body>
    <button>Right click shows the browser’s context menu</button>
    <button oncontextmenu="alert('Draw menu'); return false">
      Right click shows the context menu
    </button>
  </body>
</html>

 

Output:

Now with the context menu, implementing a document-wide context menu is also required.

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the Page</title>
  </head>
  <body>
    <p>Right click for the document’s context menu</p>
    <button id="elem">Right click the button context menu</button>
    <script>
      elem.oncontextmenu = function(event) {
        event.preventDefault();
        alert("Button context menu");
      };
      document.oncontextmenu = function(event) {
        event.preventDefault();
        alert("Document context menu");
      };
    </script>
  </body>
</html>

 

Output:

A problem will arise while clicking on elem that two menus will appear. One is button-level, and the other is document-level. This problem is solved by using the method known as event.stopPropagation().

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the Page</title>
  </head>
  <body>
    <p>Right-click for the document’s context menu</p>
    <button id="elem">Right-click for the button’s context menu (fixed with event.stopPropagation())</button>
    <script>
      elem.oncontextmenu = function(event) {
        event.preventDefault();
        event.stopPropagation();
        alert("The button’s context menu");
      };
      document.oncontextmenu = function(event) {
        event.preventDefault();
        alert("The document’s context menu");
      };
    </script>
  </body>
</html>

 

Output:

The button-level menu will work perfectly after initiating the above code. But there is a catch that any other outer code would not be allowed to access the information about the right-clicks. It can cause complications. So to prevent such a situation, one solution is using the document handler to check whether the default action is prevented or not. Like this:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the Document</title>
  </head>
  <body>
    <p>Right click on the document’s menu</p>
    <button id="elem">Right click on the button’s menu</button>
    <script>
      elem.oncontextmenu = function(event) {
        event.preventDefault();
        alert("The button’s context menu");
      };
      document.oncontextmenu = function(event) {
        if(event.defaultPrevented) return;
        event.preventDefault();
        alert("The document’s context menu");
      };
    </script>
  </body>
</html>

 

Output:

Finally, everything will work perfectly fine. We can also implement nested context menus using a single global object with a handler for document.oncontextmenu. In case of any right-click, it will check all the stored handlers and initiate the required one. In case any piece of code requiring any context menu needs to know about this object, they can use it instead of the contextmenu handler.

Practice it by yourself with the help of an online javascript compiler.

Frequently Asked Questions

What is a default action?

Default actions are sets of predefined actions that a browser perform in case of any specific event like right-clicking, clicking a link, etc. 

What does prevent default do?

The preventDefault() method is used to prevent or cancel the event if it is cancelable, meaning that the default action that is supposed to happen in case of the event will not occur.

How can we access an object’s inbuilt methods?

You can utilize (.), i.e., dot operator, to call upon the methods embedded within a particular object in JavaScript. For instance - 

  let human { … }

> human.functionName(args);

How do I stop click event propagation?

To stop an event from propagation in the capturing and bubbling phases, you call the Event. stopPropagation() method in the event handler. 

Conclusion

This article taught us how to prevent default actions and handle the events using JavaScript. We studied two ways to do that, either using event.preventDefault() or return false. We hope that this article has provided you with the help to enhance your knowledge regarding browser default actions and if you would like to learn more, check out our articles on JavaScript BOMType Conversion in JavaScript and Objects in JavaScript. Do upvote our blog to help other ninjas grow.

Refer to our guided paths on Coding Ninjas Studio to learn more about DSA, Competitive Programming, JavaScript, System Design, etc. Enroll in our courses and refer to the mock test and problems available, Take a look at the interview experiences and interview bundle for placement preparations.

Do upvote our blog to help other ninjas grow.

Merry Learning!

Live masterclass