To add a click listener for any element in the page except on 1 div with jQuery, we can add a click event listener for the body and then check which element is clicked in the click event listener.
For instance, if we have:
<div id='menu-content'>
menu
</div>
<div>
foo
</div>
Then we can add the click event listener to the body by writing:
$('body').click((evt) => {
if (evt.target.id === "menu-content") {
return
}
console.log('clicked')
});
We call click with a callback that takes the evt event object.
Then we check if evt.target.id is 'menu-content' .
If it is, we stop running the function with the return statement.
Otherwise, we log 'clicked' .
Therefore, when we click on ‘foo’, we see 'clicked' logged.
Otherwise, we see nothing in the console log.
Conclusion
To add a click listener for any element in the page except on 1 div with jQuery, we can add a click event listener for the body and then check which element is clicked in the click event listener.