Reputation: 45
I Have Created A Sidebar And It Closes If Clicked On The 'X' But I Want It To Close By Clicking Anywhere On The Screen (Except On The Scrollbar) And By Clicking On The Sidebar Button Itself.
/* Set the width of the sidebar to 250px and the left margin of the page content to 250px */
function openNav() {
document.getElementById("mySidebar").style.width = "380px";
document.getElementById("main").style.marginLeft = "380px";
}
/* Set the width of the sidebar to 0 and the left margin of the page content to 0 */
function closeNav() {
document.getElementById("mySidebar").style.width = "0";
document.getElementById("main").style.marginLeft = "0";
}
<div id="mySidebar" class="sidebar">
<p style="text-align: center; font-size: 30px;">Beep Boop<br>
<a href="javascript:void(0)" class="closebtn" onclick="closeNav()" title="Close">✕</a>
<button class="openbtn" onclick="openNav()">☵ Beep Boop</button>
Upvotes: 0
Views: 330
Reputation: 468
The easiest way is to add a click event, where you detect the content of the sidebar onClick.
And you just add a logical 'not' (bang) operator condition of the declared content. Something like this:
var sideBar = document.getElementById('mySideBar');
document.addEventListener('click', function(event) {
var sideBarIsClicked = sideBar.contains(event.target);
if (!sideBarIsClicked) {
document.getElementById("mySidebar").style.width = "0";
document.getElementById("main").style.marginLeft = "0";
}
});
Implement it in your closeNav()
function.
Let me know if you need help in the comments.
Upvotes: 2