JAVASCRIPT

Create a Custom Context Menu on Right-Click

Replace the browser's default right-click menu with a custom HTML menu, dynamically positioning it at the mouse cursor using JavaScript event listeners.

document.addEventListener('DOMContentLoaded', () => {
    const customContextMenu = document.getElementById('customContextMenu');
    const targetElement = document.getElementById('myTargetElement'); // Element to attach context menu to

    // Hide context menu initially
    customContextMenu.style.display = 'none';
    customContextMenu.style.position = 'fixed';

    targetElement.addEventListener('contextmenu', function(e) {
        e.preventDefault(); // Prevent default browser context menu

        // Position the custom menu at the mouse coordinates
        customContextMenu.style.left = e.clientX + 'px';
        customContextMenu.style.top = e.clientY + 'px';
        customContextMenu.style.display = 'block';
    });

    // Hide custom menu if clicked anywhere else
    document.addEventListener('click', function(e) {
        if (!customContextMenu.contains(e.target)) {
            customContextMenu.style.display = 'none';
        }
    });

    // Example: Add an action to a menu item
    // const firstMenuItem = customContextMenu.querySelector('.menu-item');
    // if(firstMenuItem) {
    //     firstMenuItem.addEventListener('click', () => {
    //         alert('Menu item clicked!');
    //         customContextMenu.style.display = 'none'; // Hide after click
    //     });
    // }
});
How it works: This snippet demonstrates how to implement a custom right-click context menu. It listens for the `contextmenu` event on a `targetElement`. When triggered, it prevents the default browser context menu using `e.preventDefault()`, then positions a pre-existing hidden `customContextMenu` element at the mouse cursor's coordinates (`e.clientX`, `e.clientY`) and makes it visible. A global `click` listener is added to hide the custom menu if the user clicks anywhere outside of it. This allows for rich, application-specific context-sensitive actions.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs