Conceal the Bootstrap side navigation bar upon clicking anywhere else

Is there a way to make the side nav close when clicked outside of it while using my left side bar?

Here is the code for my side nav:

//side-nav is the class of my side nav 
//leftmenutrigger is my button on the nav bar that toggles the side nav

Any suggestions or tips, whether in JavaScript or CSS, on how to hide my side nav bar are appreciated.

Below are the codes for my navigation bar and left side nav bar:

$( document ).ready(function() {
  $('.leftmenutrigger').on('click', function(e) {
     $('.side-nav').toggleClass("open"); 
     e.preventDefault();
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<nav class="navbar header-top sticky-top navbar-expand-lg  navbar-light bg-light" >
   <span class="navbar-toggler-icon leftmenutrigger"></span>
    <a class="navbar-brand" href="#">
        <img src="images/nexuslogo.png" style="width: 40px; height: 40px;padding: 0px; margin: 0px;">
    </a>
    <a class="navbar-brand" id="comp_name" name="comp_name"> Nexus Technologies, Inc.</a>
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarText" aria-controls="navbarText"
        aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon" ></span> </button>      
         
    <div class="collapse navbar-collapse" id="navbarText" name="navbarText" >
    <ul class="navbar-nav animate side-nav ">         
      <li class="nav-item">
        <a  href="" id="addUser" name="addUser" style="width: 100%"> 
          <i class="fa fa-plus-circle"></i> Add User                   
        </a>            
          <a href="manageprize.php" id="manage_prize" name="manage_prize" style="width: 100%" target="_self"> 
            <i class="fa fa-table"></i> Manage Prizes                 
         </a>                                
    </li>         
  </ul>
 </div>
</nav>

THANKS!!!!

Answer №1

Below is an example using Bootstrap 3:

<nav class="navbar navbar-default">
   <div class="container-fluid">
      <div class="navbar-header">
         <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
            <span class="sr-only">Toggle navigation</span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
         </button>
      </div>

      <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
         <ul class="nav navbar-nav">
            <li class="active"><a href="#">Link <span class="sr-only">(current)</span></a></li>
            <li><a href="#">Link</a></li>
         </ul>
      </div>
   </div>
</nav>

See the following JavaScript code that I use:

  1. Outside of .navbar-collapse :
$("body").click(function (event) {
    var target = $(event.target);
    var navbarCollapse = $(".navbar-collapse");               
    var navbarCollapseOpened = navbarCollapse.hasClass("in");
    if (navbarCollapseOpened && !target.hasClass("navbar-toggle")) {      
        navbarCollapse.collapse("hide");
    }
});
  1. Anywhere outside the .navbar element:
$("body").click(function (event) {
    var navigation = $(event.target).parents(".navbar").length;
    if(!navigation) {
        $(".navbar .navbar-collapse").collapse("hide");
    }
});

Answer №2

Implement the use of onclick for the window and remove the class show if it exists.

Additionally, utilize onclick on the navigation to prevent collapsing.

$(window).click(function(e) {

   if($(".navbar-collapse").hasClass("show")){
      $('.navbar-collapse').removeClass("show"); 
      e.preventDefault();
      }
});
 $('.navbar-collapse').click(function(event){
     event.stopPropagation();
 });
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>

<nav class="navbar header-top sticky-top navbar-expand-lg  navbar-light bg-light" >
   <span class="navbar-toggler-icon leftmenutrigger"></span>          <!--THIS IS THE BUTTON THAT TOGGLES-->
    <a class="navbar-brand" href="#">
        <img src="images/nexuslogo.png" style="width: 40px; height: 40px;padding: 0px; margin: 0px;">
    </a>
    <a class="navbar-brand" id="comp_name" name="comp_name"> Nexus Technologies, Inc.</a>
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarText" aria-controls="navbarText"
        aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon" ></span> </button>      
         
    <div class="collapse navbar-collapse" id="navbarText" name="navbarText" > //SIDE NAV BAR ITEMS
    <ul class="navbar-nav animate side-nav ">         
      <li class="nav-item">
        <a  href="" id="addUser" name="addUser" style="width: 100%"> 
          <i class="fa fa-plus-circle"></i> Add User                   
        </a>            
          <a href="manageprize.php" id="manage_prize" name="manage_prize" style="width: 100%" target="_self"> 
            <i class="fa fa-table"></i> Manage Prizes                 
         </a>                                
    </li>         
  </ul>
 </div>
</nav>

Answer №3

document.addEventListener("click", function(event) {
    // Check if user clicks inside a specific element
    if (event.target.closest(".side-nav")){
       $('.side-nav').removeClass("open"); 
    };
});

This script is designed to handle clicks outside of a certain element using jQuery.

It utilizes event bubbling, which means that when a user clicks on any element within .side-nav, the event propagates up to the document level. If somewhere along the way we find .side-nav as an ancestor of the clicked element, it indicates that the click was made inside the intended area.

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

Tips on transferring information from React frontend Hooks to the Express backend

I'm encountering an issue when attempting to send data from my React front end, which is utilizing hooks, to my Node/Express server. Upon inspecting the request object (userLog) in the Express back end, I notice that the body content is empty. Can an ...

Transferring information from a Form to various web pages using a single JavaScript source file

After successfully creating a basic login page with hardcoded credentials, I faced a challenge. While I could transition to the next page once the user logs in, I struggled to display the username entered on the first page onto the second page. I attempte ...

Converting an HTML menu to a WordPress menu: A step-by-step guide

Hey everyone, I've got some code in my HTML file that's using the 320 Bootstrap WP theme. I've created a menu and it's working fine. However, the box above the menu isn't moving along with it from menu to menu. Any ideas on how to ...

In ReactJS, the behavior of event.currentTarget differs from that of Vanilla Javascript

Is there an equivalent of event.currentTarget in ReactJS? When using event.target on click, I am getting the childDiv instead of the desired parentDiv. For example, in Vanilla Javascript: document.getElementById("parentDiv").onclick = function() { ...

Google Chrome Back Button not saving radio button selections

We have noticed an issue with Google Chrome wherein the back button does not retain radio box selections when submitting a form that contains all radio boxes. This seems to be specific to Chrome and is not observed in other browsers like IE and Firefox. B ...

Struggling with transferring a JavaScript array to the current page using AJAX

This might sound like a common question, but I have conducted thorough research and none of the solutions provided have worked for me. I have a javascript array structured as follows: [from: "2016-04-01", to: "2016-04-14"] I am sending this array via AJA ...

Attempting to reset the altered values proves ineffective in different Ctrl instances within AngularJS

I'm feeling a bit disoriented regarding my current issue. The scenario involves two views and a controller that interact with a service. The first view consists of a table list containing items loaded from a WebAPI. The service sends requests to the s ...

Is there a way to achieve the same functionality by utilizing the .then method instead of setTimeout? I encountered an issue stating "Cannot read property 'then' of undefined"

I am attempting to include a new type of bullet in the database and display a list of bullets with the newly added item. The Bullet class method "add" is used to add a new bullet type to the database: static add(bullet) { sql.on('error&ap ...

Container beyond div

Having an issue with the div extending beyond the container in Bootstrap 4. When a green div reaches the edge of the page, instead of being cut off it causes a horizontal shift in the page layout. How can this be avoided? Appreciate any assistance. Live ...

Displaying upcoming events on the current webpage using a div element

Hey there! I'm brand new to using jQuery and I'm currently working on creating an events calendar. So far, I have successfully implemented the calendar module. Currently, when I click on a specific date, it takes me to the events.php page where a ...

Is the original image source revealed when clicked?

I've implemented an expand and collapse feature using jQuery/JavaScript. Clicking on the DIV causes the image inside to change state. However, clicking on the same DIV again doesn't return the image to its original state; it remains stuck in the ...

Create a rectangle on a canvas using coordinates that have been translated relative to the original image

Displayed on the screen is an image element that undergoes a css transform: rotate(degree), with degree ranging from 0 to 360. This transformation makes the image appear rotated, even though its original orientation remains unchanged. Given this scenario, ...

Activate the Giphy search feature in the Slack Nestor bot's response

How can the nestor bot be configured to use a giphy search when replying in a Slack channel where the giphy plugin is active? Can something like msg.reply('/giphy ' + text, done); be used for this purpose? ...

Collecting Images Based on Quantity

Despite using async to download URIs on every request and closing when a certain count is reached, I am still encountering the issue of files not being downloaded properly and exiting before reaching their maximum. Can someone suggest the best solution t ...

Is there a way to separate words and specify different CSS colors for each word?

https://i.sstatic.net/a0C02.png I want to use JavaScript or jQuery to separate a word and apply CSS colors for "Hear (blue)" and "Us (black)". Below is the inspect element, and since I don't have a file to work on, I will use class names and IDs wit ...

Unable to establish connection via web socket with SSL and WSS in JavaScript

Below is the code I used to implement web socket: try { console.log('wss://' + hostname + ':' + port + endpoint); webSocket = new WebSocket(webSocketURL); webSocket.onmessage = function (event) { //c ...

The backdrop hue conceals the dropdown menu background's shade

example I am currently facing an issue related to the appearance of my webpage. The image on the left shows how it looks without a background color set for the element with ID "landing-wrap", while the one on the right includes a background color for the ...

I'm experiencing an issue with this code where it is returning the URL instead of the expected data

const http = require('http'); const xml2js = require('xml2js'); const parser = xml2js.Parser({ explicitArray: false }); const goodreadsService = function () { const getBookById = function (id, cb) { const options = { ...

Unexpected wrapping behavior in the input element when using Bootstrap grid system

While working on the email client sidebar, I encountered an issue where the content in the main body area would wrap incorrectly when the screen size decreased. I'm struggling to identify what's causing this behavior. body { background-color ...

Struggles encountered when choosing the initial visible item

I have a set of 3 tabs, each with its own heading and content. However, I only want to display the tabs that the user selects by checking the corresponding checkboxes. There are 3 checkboxes, one for each tab. Below is the code snippet: //Function to ...