search
HomeWeb Front-endCSS TutorialHow to add a custom right-click menu to a web page?

How to add a custom right-click menu to a web page?

In this day and age, when you right-click on any web page, a list pops up with some options and features. This pop-up menu is also called the context menu, which is the default pop-up menu provided by the browser. The items in this menu list will vary between browsers. Some browsers offer more features, while others offer limited features.

But here is a way to add a custom context menu or right-click menu to your web pages, with as many options as you want. But before you can add a custom context menu, you need to change the behavior of the default right-click on a web page, which opens the default context menu. Adding a custom context menu involves the following two steps:

  • Change the default behavior of showing the default right-click menu.

  • Add our own custom context menu and display it on the web page with a right mouse click.

Let us now understand the above two steps in detail step by step through actual code examples.

Remove or hide the default context menu

In order to show our custom context menu when right-clicking on a web page, first we need to remove or hide the default context menu by assigning a function containing the preventDefault() method to document.oncontextmenu event to change the default behavior of right-click, which calls this function when the user right-clicks on the web page.

Let's discuss the actual implementation of the default behavior that prevents hiding of the default context menu.

step

  • Step One − In the first step, we will create an HTML document and create a web page to test our code.

  • Step 2 - In this step, we will add the oncontextmenu event in the HTML document because the menu will pop up when right clicking on the entire web page.

  • Step 3 - In the final step, we will define a JavaScript function with a preventDefault() method or return false; statement to prevent the default context menu from popping up.

Example

The following example will illustrate how to change the default behavior of the default context menu and hide it−

<html>
<body>
      <div style = "background-color: #84abb5; color: white; height: 150px; text-align: center;">
      <h2 id="It-is-the-Demo-web-page-for-testing">It is the Demo web page for testing. </h2>
   </div>
   <script>
      document.oncontextmenu = hideRightClickMenu;
      function hideRightClickMenu(event) {
         event.preventDefault()
         // OR
         // return false;
      }
   </script>
</body>
</html>

In the above example, we saw how to remove or hide the default context menu functionality when right-clicking on a page by assigning a function using the preventDefault() method.

Let us now understand how to add a custom context menu and make it visible when right clicking on the page.

step

  • Step 1 - In the first step we will create a list of items that must be shown in the context menu and keep it shown: None; by default, only right click Click on the page to see it.

  • Step 2 - In the next step, we will use the

  • Step 3 - In the final step, we will add JavaScript functionality to the custom menu to display it on the web page after the user right-clicks on the page.

Example

The following examples will illustrate how to prevent the default context menu from being displayed, and how to add and display a custom context menu −

<html>
<head>
   <style>
      #customContextMenu {
         position: absolute;
         background-color: #84abb5;
         color: white;
         height: 150px;
         width: 100px;
         text-align: center;
      }
      .menuItems {
         list-style: none;
         font-size: 12px;
         padding: 0;
         margin: 0;
      }
      .menuItems .items { padding: 5px; border-bottom: 1px solid #e6d4b6;}
      .menuItems .items:last-child { border: none;}
      .menuItems .items a {text-decoration: none; color: white;}
   </style>
</head>
<body>
   <div style = "background-color: green; color: white; height: 150px; text-align: center;">
   <h2 id="Add-a-custom-right-click-menu-to-a-webpage"> Add a custom right-click menu to a webpage </h2>
   <p> Please right click to to see the menu </p>
   </div>
   <div id = "customContextMenu" style = "display: none;">
   <ul class = "menuItems">
   <li class = "items"><a href = "#"> Menu Item-1 </a></li>
   <li class = "items"><a href = "#"> Menu Item-2 </a></li>
   <li class = "items"><a href = "#"> Menu Item-3 </a></li>
   <li class = "items"><a href = "#"> Menu Item-4 </a></li>
   <li class = "items"><a href = "#"> Menu Item-5 </a></li>
   <li class = "items"><a href = "#"> Menu Item-6</a></li>
   </ul>
   </div>
   <script>
      // hiding the menu on click to the document
      function hideCustomContextMenu() {
         document.getElementById('customContextMenu').style.display = "none";
      }
      
      // toggling the menu on right click to the page
      function showCustomContextMenu(event) {
         event.preventDefault();
         var myContextMenu = document.getElementById('customContextMenu');
         if (myContextMenu.style.display == "block") {
            myContextMenu.style.display = "none";
         }
         else {
            myContextMenu.style.display = "block";
            myContextMenu.style.left = event.pageX + "px";
            myContextMenu.style.top = event.pageY + "px";
         }
      }
      document.onclick = hideCustomContextMenu;
      document.oncontextmenu = showCustomContextMenu;
   </script>
</body>
</html>

In this example, we hide the default context menu and display our own created context menu when right-clicking on the page, at the position of the cursor when clicked.

in conclusion

In this article, we learned how to remove or hide the default context value when right-clicking on a web page, and display our own custom context menu in the same action. In this way we can add a custom context menu with the options we want to be displayed in it.

The above is the detailed content of How to add a custom right-click menu to a web page?. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:tutorialspoint. If there is any infringement, please contact admin@php.cn delete
@keyframes CSS: The most used tricks@keyframes CSS: The most used tricksMay 08, 2025 am 12:13 AM

@keyframesispopularduetoitsversatilityandpowerincreatingsmoothCSSanimations.Keytricksinclude:1)Definingsmoothtransitionsbetweenstates,2)Animatingmultiplepropertiessimultaneously,3)Usingvendorprefixesforbrowsercompatibility,4)CombiningwithJavaScriptfo

CSS Counters: A Comprehensive Guide to Automatic NumberingCSS Counters: A Comprehensive Guide to Automatic NumberingMay 07, 2025 pm 03:45 PM

CSSCountersareusedtomanageautomaticnumberinginwebdesigns.1)Theycanbeusedfortablesofcontents,listitems,andcustomnumbering.2)Advancedusesincludenestednumberingsystems.3)Challengesincludebrowsercompatibilityandperformanceissues.4)Creativeusesinvolvecust

Modern Scroll Shadows Using Scroll-Driven AnimationsModern Scroll Shadows Using Scroll-Driven AnimationsMay 07, 2025 am 10:34 AM

Using scroll shadows, especially for mobile devices, is a subtle bit of UX that Chris has covered before. Geoff covered a newer approach that uses the animation-timeline property. Here’s yet another way.

Revisiting Image MapsRevisiting Image MapsMay 07, 2025 am 09:40 AM

Let’s run through a quick refresher. Image maps date all the way back to HTML 3.2, where, first, server-side maps and then client-side maps defined clickable regions over an image using map and area elements.

State of Devs: A Survey for Every DeveloperState of Devs: A Survey for Every DeveloperMay 07, 2025 am 09:30 AM

The State of Devs survey is now open to participation, and unlike previous surveys it covers everything except code: career, workplace, but also health, hobbies, and more. 

What is CSS Grid?What is CSS Grid?Apr 30, 2025 pm 03:21 PM

CSS Grid is a powerful tool for creating complex, responsive web layouts. It simplifies design, improves accessibility, and offers more control than older methods.

What is CSS flexbox?What is CSS flexbox?Apr 30, 2025 pm 03:20 PM

Article discusses CSS Flexbox, a layout method for efficient alignment and distribution of space in responsive designs. It explains Flexbox usage, compares it with CSS Grid, and details browser support.

How can we make our website responsive using CSS?How can we make our website responsive using CSS?Apr 30, 2025 pm 03:19 PM

The article discusses techniques for creating responsive websites using CSS, including viewport meta tags, flexible grids, fluid media, media queries, and relative units. It also covers using CSS Grid and Flexbox together and recommends CSS framework

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Atom editor mac version download

Atom editor mac version download

The most popular open source editor