Hide the menu even if the user clicks outside of it or anywhere on the webpage

I have a menubar code that is functioning correctly. However, I would like to make an enhancement. Currently, when I click outside of the menubar, it does not hide or close. I want the menubar to be hidden when I click anywhere on the webpage while the menu bar is active.

function openNav() {
    document.getElementById("mySidenav").style.width = "50%";
}
function closeNav() {
    document.getElementById("mySidenav").style.width = "0";
}
(function ($) {
    // Instantiate MixItUp:
    // $('Container').mixItUp();
    // Add smooth scrolling to all links in navbar + footer link
    $(".sidenav a").on('click', function(event) {
        event.preventDefault();
        var datanew= this.href;
        var str2 = '.html';
        if(datanew.indexOf(str2) != -1){
            window.location.href = datanew;
        }else{
            var hash = this.hash;
            $('html, body').animate({scrollTop: $(hash).offset().top}, 
            900, function(){
                alert(window.location);
                window.location.hash = hash;
            });
        }
    });
})(jQuery);
.sidenav {
    height: 100%;
    width: 0;
    position: absolute;
    z-index: 1;
    top: 0;
    right: 0;
    background-color: #ef4f50;
    overflow-x: hidden;
    padding-top: 60px;
    transition: 0.5s;
    /*max-height: 551px;*/
}
.sidenav a {
    padding: 8px 8px 8px 32px;
    text-decoration: none;
    font-size: 25px;
    color: #ffffff;
    display: block;
    transition: 0.3s
}
.sidenav a:hover, .offcanvas a:focus{
    color: #f1f1f1;
}
.closebtn {
    position: absolute;
    top: 0;
    right: 25px;
    font-size: 36px !important;
    margin-left: 50px;
}
.menu-icon
{
    color: #114576;
    font-size: 30px;
    margin-top: 40px;
    margin-left: 40px;
    cursor: pointer;
}
.control {
    margin-top: 15px;
    margin-right: 40px;
}

.menu{
    min-height: 100px;
}
<header id="header">               
                <div id="mySidenav" class="sidenav">
                    <a href="javascript:void(0)" class="closebtn" onclick="closeNav()">&times;</a>
                    <a href="index.html" class="sidenavtext">Home</a>
                    <a href="about.html" class="sidenavtext">About Us</a>
                    <a href="whatwedo.html" class="sidenavtext">What We Do</a>
                    <a href="getinvolved.html" class="sidenavtext">Get Involved</a>
                    <a href="contactus.php" class="sidenavtext">Contact Us</a>
                </div>
                        
                <div class="control">
                    <div class="col-md-4">
                        <img src="assets/img/logohome.png" class="pull-left img-responsive logo" alt="SAF Logo">  
                    </div>                            
                    <div class="col-md-8">                                
                            <!-- Use any element to open the sidenav -->
                        <span onclick="openNav()" class="pull-right menu-icon">☰</span>  
                        <button type="button" class="pull-right btn btn-danger btn-round donate">DONATE NOW</button>
                    </div>
                </div>                
        </header>        

Answer №1

Consider using something similar to this code snippet:

$(window).click(function(event) {
  if ($(event.target).closest('div#mySidenav').length === 0 && $(event.target).closest('.menu-icon').length === 0) {
    closeNav()
  }
})

This code will determine whether you clicked on "openNav" or anywhere else in the menu.

function openNav() {
  document.getElementById("mySidenav").style.width = "50%";
}

function closeNav() {
  document.getElementById("mySidenav").style.width = "0";
}
(function($) {
  // Instantiate MixItUp:
  // $('Container').mixItUp();
  // Add smooth scrolling to all links in navbar + footer link
  $(".sidenav a").on('click', function(event) {
    event.preventDefault();
    var datanew = this.href;
    var str2 = '.html';
    if (datanew.indexOf(str2) != -1) {
      window.location.href = datanew;
    } else {
      var hash = this.hash;
      $('html, body').animate({
          scrollTop: $(hash).offset().top
        },
        900,
        function() {
          alert(window.location);
          window.location.hash = hash;
        });
    }
  });
})(jQuery);

$(window).click(function(event) {
  if ($(event.target).closest('div#mySidenav').length === 0 && $(event.target).closest('.menu-icon').length === 0) {
    closeNav()
  }
})
.sidenav {
  height: 100%;
  width: 0;
  position: absolute;
  z-index: 1;
  top: 0;
  right: 0;
  background-color: #ef4f50;
  overflow-x: hidden;
  padding-top: 60px;
  transition: 0.5s;
  /*max-height: 551px;*/
}

.sidenav a {
  padding: 8px 8px 8px 32px;
  text-decoration: none;
  font-size: 25px;
  color: #ffffff;
  display: block;
  transition: 0.3s
}

.sidenav a:hover,
.offcanvas a:focus {
  color: #f1f1f1;
}

.closebtn {
  position: absolute;
  top: 0;
  right: 25px;
  font-size: 36px !important;
  margin-left: 50px;
}

.menu-icon {
  color: #114576;
  font-size: 30px;
  margin-top: 40px;
  margin-left: 40px;
  cursor: pointer;
}

.control {
  margin-top: 15px;
  margin-right: 40px;
}

.menu {
  min-height: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<header id="header">
  <div id="mySidenav" class="sidenav">
    <a href="javascript:void(0)" class="closebtn" onclick="closeNav()">&times;</a>
    <a href="index.html" class="sidenavtext">Home</a>
    <a href="about.html" class="sidenavtext">About Us</a>
    <a href="whatwedo.html" class="sidenavtext">What We Do</a>
    <a href="getinvolved.html" class="sidenavtext">Get Involved</a>
    <a href="contactus.php" class="sidenavtext">Contact Us</a>
  </div>

  <div class="control">
    <div class="col-md-4">
      <img src="assets/img/logohome.png" class="pull-left img-responsive logo" alt="SAF Logo">
    </div>
    <div class="col-md-8">
      <!-- Use any element to open the sidenav -->
      <span onclick="openNav()" class="pull-right menu-icon">☰</span>
      <button type="button" class="pull-right btn btn-danger btn-round donate">DONATE NOW</button>
    </div>
  </div>
</header>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Manipulate object position using Aframe and three.js

I'm working on developing a game using A-frame. I'm trying to add a shooting effect by incorporating a gun model that follows the user's cursor. I've coded a click event so that an object moves in front of the gun and follows the direct ...

What is the best way to obtain the present date in Nuxt directly from the server?

While conducting code tests, I realized that I required the current time from the server to run the tests effectively. In JavaScript, you can easily obtain the current date on the client side using the command: new Date();. However, when working with Nuxt ...

The ajax request functions smoothly on the OS X Paw app and cURL, but does not work properly when coded in Javascript / jQuery

Currently delving into the world of ajax requests, I've been utilizing the Paw app to troubleshoot one. Surprisingly, the request functions flawlessly within Paw itself and even the cURL code generated by Paw works like a charm. However, the JavaScrip ...

When using ViewBag in JavaScript, an error may occur with the message "Uncaught SyntaxError: Unexpected token '<'"

When I try to fetch data from an API and assign it to the VIEW BAG, I encounter an error during runtime. List<DevInfo> DevList = await RestApi.Instance.GetAllDevAsync(); var nameT = DevList.Select(a=>a.Name).ToList(); ViewBag.datasourceDevList = n ...

Tips for Implementing Show and Hide Functionality in JavaScript

I have a piece of cshtml code similar to the following: <span class="p1"> Breaking India: Western Interventions in Dravidian and Dalit Faultlines is a book authored by Rajiv Malhotra and Aravindan Neelakandan, arguing ...

react component fails to rerender upon state change

I am struggling with a React functional component that includes a file input. Despite selecting a file, the text in the h1 tag does not change from choose file to test. The handleChange function is triggered successfully. A console.log statement confirm ...

How to sanitize data by removing HTML tags in a MySQL query before inserting or selecting from a database table

My dilemma involves data that is wrapped in HTML tags. I need to transfer this data into a database table as simple text, without the accompanying HTML formatting. Is there MySQL code available that could assist in stripping out the HTML tags during eithe ...

Detach attention from TextField select component in Material UI and React through manual means

When I create a select input using the TextField component from Material-UI library, I need to manually remove focus after an option is selected. I attempted to achieve this by using a reference to the TextField with the 'inputRef' prop. However, ...

Displaying svg files conditionally in a react native application

I have developed an app specifically for trading dogs. Each dog breed in my app is associated with its own unique svg file, which are all stored in the assets folder (approximately 150 svg files in total). When retrieving post data from the backend, I re ...

Tips for creating multiple diagonal lines with CSS and HTML

Is there a way to create multiple diagonal lines within a rectangle using CSS and HTML from the start? I am interested in incorporating diagonal lines at the onset of the rectangle. Here is an example code that displays the rectangle: <div className={ ...

Difficulty with implementing authentication middleware based on a condition in Express using Node.js

Currently in the process of developing my website, which includes utilizing an API built with node.js, express, and MongoDb for the database. I am facing a challenge with creating a middleware to ensure that the USER ID matches the POSTED BY ID in a COMME ...

Automatically simulate the pressing of the enter key in a text field upon page load using Javascript

I am looking to simulate the pressing of the enter key in a text field when a page is loaded. Essentially, I want the text field to automatically trigger the enter key press event as if it had been pressed on the keyboard by the user. Below is an example o ...

When utilizing scoped slots in BootstrapVue, you may encounter an error stating "Property or method 'data' is not defined."

Greetings! I am currently in the process of learning how to utilize BootstrapVue, and I decided to reference an example from the official BootstrapVue documentation. <template> <div> <b-table :fields="fields" :items="items" foot-clone ...

The request to http://localhost:8080 from http//:localhost:3000 has been restricted due to CORS policy blocking access. This is due to the absence of the 'Access-Control-Allow-Origin' header in the

const fileStorage = multer.diskStorage({ destination: function (req, file, cb) { cb(null, "images"); }, filename: function (req, file, cb) { cb(null, uuidv4()); }, }); const fileFilter = (req, file, cb) => { if ( file.mi ...

Developing a Link Element in Angular 2

Exploring the creation of a wrapper component in Angular 2, inspired by tools like react-bootstrap. The goal is to avoid repeating the component structure each time and instead create a reusable component. The desired reusable component should have a stru ...

Utilize the full width available to create a flexible div element without any fixed sizes

I have come across similar questions, but none of them quite addressed my specific situation. My dilemma involves a tabbed navigation that can vary in size depending on the number of tabs added to it. Adjacent to the navigation, there is a second area hous ...

Determine in Typescript if a value is a string or not

In my code, I have a component: export type InputData = string | number | null; interface InputData { data?: string | number | null; validate: boolean; } const App: React.FC<InputData> = ({ data = '', validate = true, }) => ...

Determine whether the response originates from Express or Fastify

Is there a method to identify whether the "res" object in NodeJS, built with Javascript, corresponds to an Express or Fastify response? ...

Align numbers vertically inside scrollbar center

I have created a program where you can input a number, and it will count from 0 to the specified number. Currently, the numbers are aligned horizontally up to 12 before starting on a new line. However, I would like the numbers to be arranged vertically fr ...

The Interactive Menu Toggler: A jQuery Solution

$(window).on('resize', function() { if ( $( window ).width() > 768 ) { $('#menu-main-navigation').show(); } }); $('#nav-toggle').on('click', function() { // start of the nav toggle $('#m ...