Search code examples
javascripttooltip

How to Block Mouse right click menu and show tooltip on mouse right click in js


I need to hide the context menu on mouse right click on my images in my website and need to show the tool tip when user right clicks on images

I found the solution to block the right click action .That is given below

<body oncontextmenu="return false;">

Now I need to Show the tool tip when user right clicks on images.

Thanks in advance ;)


Solution

  • Well, you will need to define an event listener on the images to change the behavior. I suggest that you will need to call `event.stopPropagation to prevent the listener that you define on your body to work. It should work as the events in the JS are bubbling so they firstly trigger the most inner element and then the outer one.

    It could look in the following way.

    image.addEventListener("contextmenu", (event) => {
        event.stopPropagation();
        // some other code that you want to implement.
    });
    

    Here image is just an HTML element that you can get by the querySelector. The more advanced solution will have the following way.

    body.addEventListener("contextmenu", (event) => {
        if (event.target.tagName.toLowerCase() !== 'img') {
           return false;
        }
    });
    

    Then you will need to remove oncontextmenu listener defined in the HTML. The above code will disable the context for any click that happens not on img tag.