Saturday, June 13, 2026
HomeLanguagesJavascriptJavaScript contextmenu MouseEvent

JavaScript contextmenu MouseEvent

When we click the right mouse button on our desktop, a menu-like box appears and this box is called the context menu. In JavaScript, a context menu event runs when a user tries to open a context menu. This can be done by clicking the right mouse button. 

This article demonstrates executing any operation when we click the right mouse button. For example, we want to change the background color of a box when we click the right mouse button.

Example:

HTML




<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
</head>
 
<body>
    <div class="context">
        <p>
            Click right mouse button
          </p>
    </div>   
      <script>
        // To prevent default operation of right mouse click
        document.addEventListener("contextmenu", (e) => {
          e.preventDefault();
        });
         
        const contextMenu = document.querySelector(".context");
        contextMenu.addEventListener("contextmenu", (e) => {
          e.preventDefault();
          contextMenu.textContent = "neveropen";
          contextMenu.style = "color:green"
        });
    </script>
</body>
 
</html>


Output : 

 

Note: Using this method we can perform a lot of things, we can add a menu on our right-click.

RELATED ARTICLES

1 COMMENT

Most Popular

Dominic
32515 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
6897 POSTS0 COMMENTS
Nicole Veronica
12013 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12109 POSTS0 COMMENTS
Shaida Kate Naidoo
7019 POSTS0 COMMENTS
Ted Musemwa
7262 POSTS0 COMMENTS
Thapelo Manthata
6976 POSTS0 COMMENTS
Umr Jansen
6964 POSTS0 COMMENTS