I have some elements which i can select with .click() function and they became highlighted. There is menu above them with some actions. I want to cancel highlight when I click any element but not menu.
Structure:
<body>
<div id="menu">
</div>
<div id="elements">
/* selectable elements here */
</div>
</body>
Executable Example
$().ready(function(){
$("#elements a").click(function(){
$(this).css('color', 'red');
return false;
});
$(document).click(function(e) {
if ( $(e.target).closest('#menu').length === 0 ) {
$("#elements a").css('color', 'blue');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="menu">
<a href="#">Menu 1</a>
<a href="#">Menu 2</a>
<a href="#">Menu 3</a>
</div>
<div id="elements">
<a href="#">Element 1</a>
<a href="#">Element 2</a>
<a href="#">Element 3</a>
</div>
<div>
Click any element to highlight it. Click anywhere to reset highlighting. Click menu to keep highlighting.
</div>
I tried to bind $("body *").not("#menu").click(...);
but when I click on #menu then body's onclick event fired too because #menu is body's children.