I have a header
section which contains a submenu.
When a user click outside of header
, I'm looking to hide the submenu.
For now, I'm simply trying to console.log
when clicking anywhere except when clicking on the header
.
I've seen similar articles on SO, however, they don't work in my instance.
My console.log
's are still appearing when I click on the header
?
$(function () {
// $('html:not(.globalHeader)').click(function(event){
// event.stopPropagation();
// console.log("click");
// });
$("body")
.not(".globalHeader")
.on("click", function (e) {
e.preventDefault();
console.log("click");
});
});
header {
padding: 20px 0;
background: black;
color: white;
text-align: center;
}
.spacer {
height: 100vh;
background: lightblue;
display: flex;
justify-content: center;
align-items: center;
margin-top: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js" integrity="sha512-aVKKRRi/Q/YV+4mjoKBsE4x3H+BkegoM/em46NNlCqNTmUYADjBbeNefNxYV7giUp0VxICtqdrbqU7iVaeZNXA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<body>
<header class="globalHeader">Header</header>
<div class="spacer">Spacer</div>
</body>