How to Add a Click Listener for Any Element in the Page Except on 1 Div with jQuery?
Sometimes, we want to add a click listener for any element in the page except on 1 div with jQuery.
In this article, we’ll look at how to add a click listener for any element in the page except on 1 div with jQuery.
Add a Click Listener for Any Element in the Page Except on 1 Div with jQuery
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.
In Plain English 🚀
Thank you for being a part of the In Plain English community! Before you go:
- Be sure to clap and follow the writer ️👏️️
- Follow us: X | LinkedIn | YouTube | Discord | Newsletter
- Visit our other platforms: Stackademic | CoFeed | Venture | Cubed
- More content at PlainEnglish.io
