How to show some custom menu on text selection?

In text editors like Microsoft Word, selecting text reveals a custom menu with formatting options like bold, italic, color changes, and alignment controls. This tutorial demonstrates how to create a similar custom context menu that appears when users select text on a webpage.

How It Works

The technique involves capturing mouse coordinates during selection and positioning a custom menu at the selection point. We use the getSelection() API to detect when text is selected and getBoundingClientRect() to calculate the menu position.

Implementation Steps

  • Step 1 ? Create HTML structure with content div and hidden custom menu
  • Step 2 ? Capture mouse coordinates on mousedown event using pageX and pageY
  • Step 3 ? On mouseup, check if text is selected using getSelection().toString()
  • Step 4 ? Calculate menu position relative to the content container
  • Step 5 ? Show menu at calculated coordinates or hide if no text selected

Example

This example creates a custom menu with "Copy" and "Cut" options that appears when text is selected:

<html>
<head>
   <style>
      .content {
         padding: 20px;
         font-family: Arial, sans-serif;
         position: relative;
      }
      .hoverMenu { 
         display: none; 
         position: absolute; 
         background: #333; 
         border-radius: 6px; 
         height: 35px;
         padding: 5px;
         box-shadow: 0 2px 8px rgba(0,0,0,0.2);
      }
      .hoverMenu span{ 
         color: white; 
         cursor: pointer; 
         margin: 8px;
         padding: 5px 10px;
         border-radius: 3px;
      }
      .hoverMenu span:hover {
         background: #555;
      }
   </style>
</head>
<body>
   <div class="content">
      <h2>Custom Text Selection Menu</h2>
      <p>Select any text below to see the custom menu appear:</p>
      <p>TutorialsPoint is an online platform that provides free tutorials and resources on various programming languages, software tools, and technologies. It offers comprehensive learning materials for beginners and advanced developers.</p>
      <div class="hoverMenu"> 
         <span onclick="copyText()">Copy</span> 
         <span onclick="cutText()">Cut</span> 
      </div>
   </div>
   <script>
      var clientX, clientY;
      
      // Capture mouse position on mousedown
      document.addEventListener("mousedown", function (event) { 
         clientX = event.pageX; 
         clientY = event.pageY;
      });
      
      // Handle text selection on mouseup
      document.addEventListener("mouseup", () => {
         let selectionFromDocument = document.getSelection();
         let textValue = selectionFromDocument.toString().trim();
         var hoverMenu = document.querySelector(".hoverMenu");
         
         if (textValue === "") { 
            hoverMenu.style.display = "none";
         } else {
            // Get coordinates of the content div
            let coordinates = document.querySelector(".content").getBoundingClientRect();
            
            // Show menu
            hoverMenu.style.display = "flex";
            
            // Calculate and set menu position
            let posX = clientX - Math.round(coordinates.left) + "px";
            let posY = clientY - Math.round(coordinates.top) - 40 + "px";
            
            hoverMenu.style.left = posX;
            hoverMenu.style.top = posY;
         }
      });
      
      // Hide menu when clicking elsewhere
      document.addEventListener("click", (event) => {
         if (!event.target.closest(".hoverMenu")) {
            document.querySelector(".hoverMenu").style.display = "none";
         }
      });
      
      // Menu functionality
      function copyText() {
         let selectedText = document.getSelection().toString();
         navigator.clipboard.writeText(selectedText);
         document.querySelector(".hoverMenu").style.display = "none";
      }
      
      function cutText() {
         let selectedText = document.getSelection().toString();
         navigator.clipboard.writeText(selectedText);
         document.getSelection().deleteFromDocument();
         document.querySelector(".hoverMenu").style.display = "none";
      }
   </script>
</body>
</html>

Key Features

  • Position Calculation ? Menu appears near the selected text using mouse coordinates
  • Selection Detection ? Uses getSelection() to check if text is selected
  • Clipboard Integration ? Copy and cut functions use the Clipboard API
  • Click-away Hiding ? Menu disappears when clicking elsewhere

Browser Compatibility

This solution works in all modern browsers. The Clipboard API requires HTTPS in production. For older browsers, consider using document.execCommand() as a fallback.

Conclusion

Custom text selection menus enhance user experience by providing contextual actions. The key is capturing mouse coordinates and positioning the menu relative to the selected text using JavaScript's selection and positioning APIs.

Updated on: 2026-03-15T23:19:01+05:30

924 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements