Is there a way for me to automatically close the navbar by clicking anywhere on the body of

Here is the structure of my navigation bar:

<div id="mySidenav" class="sidenav">
        <a href="javascript:void(0)" class="closebtn" onclick="closeNav()">&times;</a>
        <span class="d-flex mx-3">
          <img src="{{ asset('images/logo-small.png') }}" width="30" height="30" alt="Deliveboo">
          <h4 class="mx-3">Deliveboo</h4>
        </span>
        <hr class="mx-3">
        <div class="d-flex justify-content-center p-3">
          @if (Auth::guest())
            <a class="btn btn-primary text-center" href="{{ route('login') }}"
              role="button">Accedi</a>
            <a class="btn btn-primary text-center" href="{{ route('register') }}"
              role="button">Registrati</a>
          @endif
          @if (Auth::check())
            <a class="btn btn-primary" href="{{ route('restaurants.dashboard') }}" role="button">Vai
              alla tua dashboard</a>
          @endif
        </div>
        <hr class="mx-3">
      </div>

Below is the code for JavaScript functions:

<script>
  function openNav() {
    document.getElementById("mySidenav").style.width = "375px";
    document.getElementById("root").style.overflow = "hidden";
  }

  function closeNav() {
    document.getElementById("mySidenav").style.width = "0";
    document.getElementById("root").style.overflow = "auto";
  }
</script>

I need to add functionality to close the navbar on clicking outside of it since I am new to JavaScript.

Here is the entire view:

<body id="root">
{{-- HEADER --}}
<header>
...
</header>

{{-- MAIN --}}
<main>
  {{-- DELIVEBOO SECTION  --}}
  <section id="deliveboo-section" class="my-5">
   ...
  </section>

  {{-- DEFAULT SECTION  --}}
  <section id="default-section" class="py-5">
    ...
  </section>

  {{-- SECTION SUGGESTED  --}}
  <section id="suggested" class="m-5">
    ...
  </section>
</main>

            

Answer №1

If you want to close the sideBar navigation when it is open, you can add a listener to the body element and call the closeNav function. Additionally, you can attach a click listener to prevent the event propagation when clicking inside the navigation bar.

    <script>
       // Storing references to DOM elements to avoid repeated queries
       const sideNavBarElem = document.getElementById("mySidenav");
       const rootElem = document.getElementById("root");
       const bodyElem = document.querySelector('body');

       function openNav() {
          sideNavBarElem.style.width = "375px";
          rootElem.style.overflow = "hidden";
          // Delay attaching body listener to avoid immediate activation upon opening
          setTimeout(function() {
             bodyElem.addEventListener('click', bodyNavListener);
          }, 0);
       }

       function closeNav() {
          sideNavBarElem.style.width = "0";
          rootElem.style.overflow = "auto";
          bodyElem.removeEventListener('click', bodyNavListener);
       }
       
       function bodyNavListener(){
          // Close the navigation bar if it is open
          if(sideNavBarElem.style.width !== "0"){
             closeNav();
          }
       }
       
       sideNavBarElem.addEventListener('click', function(event){
             // Prevent event propagation to avoid closing the navigation bar unintentionally
          event.stopPropagation();
       })
    
    </script>

Check out this sample on Codepen

Answer №2

To target a different element, you can add an eventListener on the specific area using event.target. Ensure that you only add the listener when the navigation is open and remember to remove it when the navigation is closed using removeEventListener() to avoid unnecessary load.

Answer №3

To effectively close the navigation sidebar, you should attach an event listener to the body element and then execute the corresponding function.

const body = document.querySelector('body');
const buttonToOpen = document.querySelector('#buttonSideNav')

function closeNavBody(e) {
  if (e.target.id !== 'mySidenav' || e.target.id !== '#buttonSideNav') {
    closeNav();
    body.removeEventListener('click', myClick);
  }
}

function openNav() {
  document.getElementById("mySidenav").style.width = "375px";
  document.getElementById("root").style.overflow = "hidden";
  body.addEventListener('click', closeNavBody)
}

function closeNav() {
  document.getElementById("mySidenav").style.width = "0";
  document.getElementById("root").style.overflow = "auto";
}

Answer №4

Retrieve references to the necessary elements

    const mySideNav = document.getElementById("mySidenav");
    const root =  document.getElementById("root");
    const body = document.getelementByTagName("body");

Define the required functions

    function closeNav() {
         mySidenav.style.width = "0";
         root.style.overflow = "auto";
         body.onclick = undefined;
    }

    function openNav() {
     mySideNav.style.width = "375px";
      root.style.overflow = "hidden";
      body.onclick = closeNav;
    }

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

Could anyone clarify the workings of the async function in this specific useEffect situation?

Within a child component, there is an onClick event: onClick={()=>{ //2. an image is clicked, and the choice is added to the choiceOrder state, and then a jsonupdate is called -- 3. in ChooseBy.js //onclick, add or remove the choice choosebyprop ...

Instead of modifying the selected class, jQuery generates inline styles

Utilizing the following code to dynamically create a class: $("head").append('<style type="text/css"></style>'); var newStyleElement = $("head").children(':last'); newStyleElement.html('.move{transform: translateX(1 ...

Creating a User Authentication System using Node.js and Express

I am currently working on developing an application with node.js and expressJs, even though I come from a PHP background. In PHP, we typically use the session to handle logins, so naturally, I thought that in the case of node.js it would be similar. After ...

Tips for verifying elements using the Loop technique in a JSON array

I am new to JavaScript and I have been trying to run the following code with an expected result like this: [["00:04:12","05:54:46"],["06:06:42","12:45:22"],["12:51:11","15:56:11"]] However, my script is not working as expected. Can someone please help ...

Error with Chakra UI and React Hook Form mismatched data types

Struggling with creating a form using ChakraUI and React-Hook-Form in TypeScript. The errors seem to be related to TypeScript issues. I simply copied and pasted this code from the template provided on Chakra's website. Here is the snippet: import { ...

Selecting the child checkbox within the parent div using ng-click

Is there a way to trigger the click event of a parent div on its child checkbox in AngularJS? The Checkbox will have the attribute hidden, necessitating the parent div to act as the clickable element. Sample HTML: <body ng-app="checkboxApp"> ...

Looking for a list of events in Express.js?

I've been searching through the official documentation, but I couldn't find a list of events for express. Does anyone know if there's something like 'route-matched' so that I can use app.on('route-matched', () => {})? ...

Callbacks for AJAX responses that are asynchronous

After using AJAX in a limited and straightforward manner for some time, I find myself currently debugging a web application that heavily relies on JavaScript and JQuery for client-side coding. One issue that has caught my attention is the possibility of mu ...

Interactive JavaScript button that navigates me to a document without the need to click

I'm facing an issue with my small project. I've been learning javascript and managed to create a script that calculates the square of a number provided by the user. var checkIt = function(){ var theNumber = Number(prompt("Please enter a number ...

Is there a way to determine if an npm package is compatible with ES6 import syntax for importing?

Aside from reviewing the documentation of the package and trying different methods through trial and error, how can one be certain if an npm package can be imported using the ES6 import syntax? Is there a specific file within the package folder that can b ...

incorporating my unique typographic styles into the MUI framework

I'm currently working on customizing the typography for my TypeScript Next.js project. Unfortunately, I am facing difficulties in configuring my code properly, which is causing it to not work as expected. Can someone kindly provide assistance or guida ...

"The authentication scheme is unrecognized" - this is the message produced by Node-LinkedIn module

I am currently utilizing the node-linkedin npm package to authenticate and retrieve information about other users, such as their name, job title, company name, profile picture, and shared connections. While I am able to successfully receive and store the a ...

What are the steps for leveraging a proxy with NodeJS and Selenium?

While researching the topic on proxies in the documentation, I came across a method to set up a proxy while building a driver like this: var driver = new webdriver.Builder() .withCapabilities(webdriver.Capabilities.chrome()) .setProxy(proxy.manual ...

What's the reason for the malfunction of the "required" attribute in my Angular form?

I'm a beginner when it comes to using Angular. Here's the template I've set up for a Register page in Angular. All labels and inputs are enclosed within the form tag. However, I'm facing an issue where the default behavior of 'requ ...

Difficulty accessing context.params query in Next.js Dynamic Path

I've almost completed setting up a dynamic page in Next.js using getStaticPaths(), but I'm running into an issue with the getStaticProps() function not referencing the URL query correctly to load the relevant information. Here is my code: //Get ...

Discover the process of incorporating two distinct component structures within a single React application

In my React app, I am trying to implement a different navbar for routes that start with "admin". For example: Normal Page: <NormalNavbar/> <NormalHeader/> <NormalBody/> <NormalFooter/> But if it's an admin route, then I want: ...

I am finding my program to be lacking efficiency. Is there a more concise method for solving this issue?

Starting off with my journey in Javascript, I am eager to tackle problems and enhance my skills. One challenge that came my way is the following question. Despite my efforts to solve it step by step, I feel like there might be room for improvement in my co ...

Looking to shrink the image dimensions for optimal mobile display using bootstrap

In one section, I have two columns - one for an image and one for text. https://i.sstatic.net/QMLNF.png Here is the HTML code: <div class="row aboutRow"> <div class="col-lg-3 col-sm-2 col-xs-3 col-md-3 text-center"> ...

Modify the innerHTML to adjust font size when a button is clicked in Ionic 5, or eliminate any unnecessary spaces

I have been experimenting with changing the font size of a variable in .html when the variable contains whitespace. In my .ts page, I use the following code to remove the whitespace: this.contents = this.sanitizer.bypassSecurityTrustHtml(this.product[&apos ...

Fetching images using node.js via URL

I must apologize for my lack of knowledge about node.js. I am trying to read an image from a URL and resize it using sharp. Currently, my code only works for reading local images. For instance, I would like to read the following image from a URL: url= ...