I'm creating menu that appears at the top of the screen. When user clicks one of menu items div with a lot of links appear. I wan't to be able to hide this div by clicking another menu item (no problem, already implemented it) but also by clicking anywhere else then this div and menuitems.
I heard about two solutions:
- Show invisible div that is behind the menu and covers whole screen and add click handler to it.
- Attach event handler to document.body.
First one is not good for me because that div will cover links that are on the page and I want them to be clickable even after menuitem is clicked and it's corresponding div appeared. So I tried second soultion. But the problem is that jquery click handler on body is fired before my component's handler. I have no idea how to make it first call my components handler and then prevent event propagation.
Here is the code and js fiddle:
/** @jsx React.DOM */
var Menu = React.createClass({
click: function(e) {
console.log('component handled click - should be called before jquery one and prevent jquery handler from running at all');
e.stopPropagation();
},
render: function(){
console.log("component renders");
return (
<div>
<div>| MenuItem1 | MenuItem2 | MenuItem 3 |</div>
<br />
<div className="drop">
MenuItem 1 (This div appears when you click menu item)
<ul>
<li><a href="#" onClick={this.click}>Item 1 - when I click this I don't want document.body.click to fire</a></li>
<li><a href="#" onClick={this.click}>Item 1 - when I click this I don't want document.body.click to fire</a></li>
</ul>
</div>
</div>
);
}
});
React.renderComponent(<Menu />, document.getElementById("menu"));
$(document).ready(function() {
console.log('document is ready');
$("body").click(function() {
console.log('jquery handled click - should not happen before component handled click');
});
});
startup console before you run it for explanation of problem