JSFiddle - React, Tailwind, and code Playground
HTML
<div class="mainNav">
Click me to show the main nav menu
<ul>
<li>page 1</li>
<li>page 2</li>
<li>page 3</li>
<li>page 4</li>
<li>page 5</li>
</ul>
</div>
<div class="mainContent">
<p>Hello, I'm the main content of the page </p>
<button onclick="showPopup()">I should NOT fire my code if clicked to close the menu</button>
</div>
CSS
.mainNav ul {
display: none;
}
.mainNav.menuVisible ul {
display: block;
}
JavaScript
$(document).ready(function() {
$('.mainNav').click(function(e) {
//to stop window.onclick event closing the menu straight away
e.preventDefault();
$('.mainNav').addClass('menuVisible');
})
$('button[onclick]').each(function(){
$(this).data('onclick', this.onclick);
this.onclick = function(event) {
if($('.mainNav').hasClass('menuVisible')) {
return false;
};
$(this).data('onclick').call(this, event || window.event);
};
});
//When any html is clicked
$(window).click(function(e) {
if (!e.isDefaultPrevented()) {
if ($('.mainNav').hasClass('menuVisible')) {
//stop any other actions happening (e.g. following a link)
e.preventDefault();
//Hide the menus
$('.mainNav').removeClass('menuVisible');
}
}
});
});
function showPopup() {
alert("I am an alert box");
}