简体   繁体   中英

Hide context menu on outside click

I have a context menu that appears when you right click inside the <div> , and it only goes away if the user click left click inside the <div> again. How do i hide it when a user click anywhere on the page?

my fiddle

change these two functions to the following:

_onPageClick: function(e) {
   e.stopPropagation()
   if (this.refs.contextMenu.getDOMNode() !== e.target){
     this.contextMenu.setState({contextMenuLocation: ''});
   }
},

componentDidMount: function(){
    this.contextMenu = this.refs.contextMenu;
    document.addEventListener('click', this._onPageClick)
},

all we have to do is to move _onPageClick from the wrapper div to a listener on the document. the above code will close the menu if the user clicks anywhere that is not inside the context menu. if you want it to close if the user clicks the context menu as well, then change _onPageClick to:

_onPageClick: function(e) {
   e.stopPropagation()
   this.contextMenu.setState({contextMenuLocation: ''});
}

(also, the wrapper div should no longer have the onClick handler) http://jsfiddle.net/yikevinqu/eeu9unhm/1/

Check out Ben Alman's clickoutside jQuery plugin. Even if you are not using jQuery, you can review his mechanism for catching these click events as they bubble up.

http://benalman.com/projects/jquery-outside-events-plugin/

All click events get bubbled up through the DOM, so if you click an inner element, if you don't event.stopPropagation() , it will bubble up to the parent element. So just catch the click on the parent element (can even be document to hide your context menu).

Check out my fiddle for a pure JS example: http://jsfiddle.net/jsc8zLaj/

There's actually an existing React mixin on npm you can use for this:

https://github.com/Pomax/react-onclickoutside

Since mixins have fallen out of favour now, you may want to implement it as a wrapper component instead, but this is an excellent starting point.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM