Skip to content
Advertisement

How to test if contextmenu is open or displayed?

I have a page with a few pre tags in it containing computer code. I have a mouseover event listener, which highlights all the code in the pre tag. I also have it remove the highlighting on a mouseout event. Works real well if you use the keyboard to copy (ctrl-C).

But if you want to right-click and copy from the context menu, there is a problem. The moment the mouse enters the context menu, it triggers the mouseout event of the pre tag.

I need a way to test if the context menu is currently open or displayed. Then I can cancel removing the highlighting. Is there a way to test if the context menu is open or displayed?

I don’t want anything jquery, please.

My final alternative to this problem might be the oncontextmenu, but I don’t know how I would find out if it closes. Unless I try an event listener for the mouseout event of the context menu, if posible.

Here’s my code so far:

JavaScript

Advertisement

Answer

As there is no event in JS to trigger the closing action of the context menu box and no reliable workarround: so far as I know from different researches the answer to your question is no.

But there is a way to solve your problem with an custom context menu if you may think about a similar method.

Short explanation

  1. Add a custom context menu to your code and pre elements. In your case there is only one item copy needed (in the example quick! and very! simplified! demonstrated as simple box).
  2. When open the menu deactivate right click to avoid stopping the selection of your code (was your question/issue as I understand)
  3. When open the menu deactivate right click on other elements so you don’t have other context menus open
  4. When click on menu item start copy action close and reset
  5. When click outside menu close and reset

SIMPLIFIED example

Please notice: the example is a QUICK, DIRTY AND VERY SIMPLIFIED example to demonstrate the technique. I tsure needs to be adapted to your special project.

JavaScript
JavaScript
JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement