Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to hide the context menu on clicking outside uisng JS?

I have a context menu which will open on clicking any node in this network graph. And I am trying to close the context menu on clicking anywhere outside using Javascript.

I have tried to hide it using document.onclick" but its not working.

Please refer the jsfiddle link for code snippet.

Context menu should be closed on click of outside.

jsfiddle

<div id="contextMenuId" style="display: none" class="contextMenu">
    <div id="contextMenuItem1" class="sublot">menu1</div>
    <div id="contextMenuItem2">menu2</div>
</div>

plotOptions: {
        series: {
            cursor: 'pointer',
            events: {
                click: function (event) {  
                    let contextMenu = document.getElementById('contextMenuId');
                    contextMenu.onclick = function() {
                      contextMenu.classList.add("contextMenu"); 
                    }
                    /* document.onclick = function() {
                      contextMenu.style.display = 'none';
                    } */
                    contextMenu.setAttribute('style', 'top: ' + event.pageY + 'px; left:'
                      + event.pageX + 'px;');
                }
            }
        },
        networkgraph: {
            keys: ['from', 'to'],
            layoutAlgorithm: {
                enableSimulation: true,
                friction: -0.9
            }
        }
    },
like image 982
Vivek Avatar asked Sep 03 '25 05:09

Vivek


1 Answers

Add a click listener to document and try to check if it is clicked inside of your container element or outside. If clicked inside, the closest method will return parent container (it will give you the container element), else if clicked out side it will give null. We are interested in null (clicked outside) then we will hide the context menu div

document.addEventListener('click', function(e){
  let inside = (e.target.closest('#container'));
  if(!inside){
    let contextMenu = document.getElementById('contextMenuId');
    contextMenu.setAttribute('style', 'display:none');
  }
});

If you need to set a boundary other than this, just replace #container with anything suitable.

Few browsers don't yet support closest if you are not using jQuery make sure you use the pollyfill for function closest https://developer.mozilla.org/en-US/docs/Web/API/Element/closest

Updated fiddle https://jsfiddle.net/28tvp30b/

NOTE: your container element is almost taking up the whole page its tough to click outside of container. Check if you are actually clicking outside container element.

like image 195
joyBlanks Avatar answered Sep 04 '25 17:09

joyBlanks