Html5 - onContextMenu, block other events

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 deactivated, and by using this way they are still active. Is there any way to disable them?

This is because I am using a div with a position: fixed , with a top and a left equal to pageX and pageY of the click event. By zooming, scrolling div changes position.

Note: I am using a reactjs environment.

    
asked by anonymous 07.12.2018 / 09:33

1 answer

1

You can cancel events mousewheel and keydown when you open 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>
    
07.12.2018 / 12:40