Html5 - onContextMenu, block other events

Asked

Viewed 42 times

0

Hello, I’m using the onContextMenu event with e.preventDefault(), to create a custom menu. The problem is that if it is the "native" behavior of the browser, events like Scroll and Zoom are deactivative, and when using it in this way remain active. Is there any way to disable them?

That’s because I’m wearing a div com a position: fixed, with a top and a left equal to pageX and pageY click event. When zooming, and scroll the div changes the position.

Note: I am using a reactjs environment.

1 answer

1


You can cancel the events mousewheel and keydown when opening the menu:

document.addEventListener("mousewheel", noWheelZoom);
document.addEventListener("keydown", noWheelZoom);

function noWheelZoom(e){
   e.preventDefault();
}

When closing the menu, remove the events:

document.removeEventListener("keydown", noWheelZoom);
document.removeEventListener("mousewheel", noWheelZoom);

Example:

function noWheelZoom(e){
   e.preventDefault();
}

document.oncontextmenu = function(e){
   e.preventDefault();

   document.addEventListener("mousewheel", noWheelZoom);
   document.addEventListener("keydown", noWheelZoom);

   var posX = e.pageX;
   var posY = e.pageY;
   var win_scroll = window.pageYOffset || document.documentElement.scrollTop;

   var menu = document.getElementById("menu");
   menu.style.display = "block";
   menu.style.left = posX+"px";
   menu.style.top = (posY-win_scroll)+"px";
   
   menu.onclick = function(e){
      e.stopPropagation();
   }
}

document.onclick = function(e){
   menu.style.display = "none";
   document.removeEventListener("keydown", noWheelZoom);
   document.removeEventListener("mousewheel", noWheelZoom);
}
#menu{
   width: 100px;
   height: 100px;
   display: none;
   position: fixed;
   background: red;
}
<div style="height: 1000px;">
   <div id="menu"></div>
</div>

  • This solution is almost perfect, I just needed to know if there is an event that detects the click outside of the browser, this because when doing the zoom works manually. So if it was possible to detect when it was clicked outside the page, hide the menu. Is there an event for this purpose? Thank you

  • What exists is an event when the mouse leaves the page.

  • And can you tell me what that event is? Thank you very much

  • Seria document.onmouseleave = function(){ }

  • Thank you, it worked perfectly

Browser other questions tagged

You are not signed in. Login or sign up in order to post.