Switching the display of a Bootstrap navigation dropdown

After building a Bootstrap menu with a lightbox effect that overlays the page content when expanded, I encountered some issues.

I attempted to use JavaScript functions to hide and display the lightbox_container element when toggling the nav. However, adding the second function to toggle the nav off when clicking outside of it on the lightbox_container resulted in unexpected behavior, as it would set the dropdown to display:none, preventing it from expanding again.

$("#navbarSupportedContent").on('show.bs.collapse hide.bs.collapse', function(e) {
  var lightbox = document.getElementById("lightbox_container");
  if (e.type == 'hide') {
    lightbox.style.display = "none";
  } else if (e.type == 'show') {
    lightbox.style.display = "block";
  }
});

$("#lightbox_container").on("click", function() {
  if ($("#navbarSupportedContent").hasClass("show")) {
    $("#navbarSupportedContent").hide();
  }
  var lightbox = document.getElementById("lightbox_container");
  lightbox.style.display = "none";
});
#lightbox_container {
  position: fixed;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 40;
  display: none;
  top: 0px;
  left: 0px;
}

nav {
  z-index: 50;
  background-color: red;
}

.icon {
  border: 1px solid black;
  padding: 5px;
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>

<nav class="navbar navbar-expand-lg">
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="SupportedContent" aria-expanded="false" aria-label="Toggle navigation">
    <img src="media/icons/menu.png" alt="" class="icon">
  </button>
  <div class="collapse navbar-collapse" id="SupportedContent">
    <ul class="navbar-nav mx-auto">
      <li class="nav-item text-center dropdown">
        <a class="nav-link nav dropdown-toggle products-dropdown" href="#" data-toggle="dropdown" aria-expanded="false">Products</a>
        <ul class="dropdown-menu">
          <li class="dropdown-item d-block">
            <a class="submenu-item" href="store">All Products&nbsp;›</a>
          </li>
          <li class="dropdown-item d-block">
            <a class="submenu-item" href="store#1">Heading 1 ›</a>
            <ul class="dropdown-submenu">
              <li class="dropdown-item d-block"><a href="1">1</a></li>
              <li class="dropdown-item d-block"><a href="2">2</a></li>
              <li class="dropdown-item d-block"><a href="3">3</a></li>
              <li class="dropdown-item d-block"><a href="4">4</a></li>
            </ul>
          </li>
          <li class="dropdown-item d-block">
            <a class="submenu-item" href="store#2">Heading 2 ›</a>
            <ul class="dropdown-submenu">
              <li class="dropdown-item d-block"><a href="1">1</a></li>
              <li class="dropdown-item d-block"><a href="2">2</a></li>
              <li class="dropdown-item d-block"><a href="3">3</a></li>
              <li class="dropdown-item d-block"><a href="4">4</a></li>
            </ul>
          </li>
          <li class="dropdown-item d-block">
            <a class="submenu-item" href="store#3">Heading 3 ›</a>
            <ul class="dropdown-submenu">
              <li class="dropdown-item d-block"><a href="1">1</a></li>
              <li class="dropdown-item d-block"><a href="2">2</a></li>
              <li class="dropdown-item d-block"><a href="3">3</a></li>
              <li class="dropdown-item d-block"><a href="4">4</a></li>
            </ul>
          </li>
        </ul>
      </li>
      <li class="nav-item text-center"><a class="nav-link nav" href="blog">Blog</a></li>
      <li class="nav-item text-center"><a class="nav-link nav" href="about">About Us</a></li>
      <li class="nav-item text-center"><a class="nav-link nav" href="contact">Contact Us</a></li>
    </ul>
  </div>
</nav>

<div id="lightbox_container"></div>

Answer №1

Instead of using

$("#navbarSupportedContent").hide();
, it is recommended to remove the show class with the following code:

$("#SupportedContent").removeClass("show");

Check out the script below for a demonstration:

$("#SupportedContent").on('show.bs.collapse hide.bs.collapse', function(event) {
  var lightbox = document.getElementById("lightbox_container");
  if(event.type == 'hide'){
    lightbox.style.display = "none";
  }else if(event.type == 'show'){
   lightbox.style.display = "block";
  }
});
$("#lightbox_container").on("click", function(){
  if($("#SupportedContent").hasClass("show")){
    $("#SupportedContent").removeClass("show");
  }
  var lightbox = document.getElementById("lightbox_container");
  lightbox.style.display = "none";
});
#lightbox_container{
  position:fixed;
  width:100%;
  height:100%;
  background-color:rgba(0,0,0,0.5);
  z-index:40;
  display:none;
  top:0px;
  left:0px;
}
nav{
  z-index:50;
  background-color:red;
}
.icon{
  border:1px solid black;
  padding:5px;
}

body { height: 2000px; }
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>

<nav class="navbar navbar-expand-lg">
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#SupportedContent" aria-controls="SupportedContent" aria-expanded="false" aria-label="Toggle navigation">
    <img src="media/icons/menu.png" alt="" class="icon">
  </button>
  <div class="collapse navbar-collapse" id="SupportedContent">
    <ul class="navbar-nav mx-auto">
      <li class="nav-item text-center dropdown">
        <a class="nav-link nav dropdown-toggle products-dropdown" href="#" data-toggle="dropdown" aria-expanded="false">Products</a>
        <ul class="dropdown-menu">
          <li class="dropdown-item d-block">
            <a class="submenu-item" href="store">All Products&nbsp;›</a>
          </li>
          <li class="dropdown-item d-block">
            <a class="submenu-item" href="store#1">Heading 1 ›</a>
            <ul class="dropdown-submenu">
              <li class="dropdown-item d-block"><a href="1">1</a></li>
              <li class="dropdown-item d-block"><a href="2">2</a></li>
              <li class="dropdown-item d-block"><a href="3">3</a></li>
              <li class="dropdown-item d-block"><a href="4">4</a></li>
            </ul>
          </li>
          <li class="dropdown-item d-block">
            <a class="submenu-item" href="store#2">Heading 2 ›</a>
            <ul class="dropdown-submenu">
              <li class="dropdown-item d-block"><a href="1">1</a></li>
              <li class="dropdown-item d-block"><a href="2">2</a></li>
              <li class="dropdown-item d-block"><a href="3">3</a></li>
              <li class="dropdown-item d-block"><a href="4">4</a></li>
            </ul>
          </li>
          <li class="dropdown-item d-block">
            <a class="submenu-item" href="store#3">Heading 3 ›</a>
            <ul class="dropdown-submenu">
              <li class="dropdown-item d-block"><a href="1">1</a></li>
              <li class="dropdown-item d-block"><a href="2">2</a></li>
              <li class="dropdown-item d-block"><a href="3">3</a></li>
              <li class="dropdown-item d-block"><a href="4">4</a></li>
            </ul>
          </li>        
        </ul>
      </li>
      <li class="nav-item text-center"><a class="nav-link nav" href="blog">Blog</a></li>
      <li class="nav-item text-center"><a class="nav-link nav" href="about">About Us</a></li>
      <li class="nav-item text-center"><a class="nav-link nav" href="contact">Contact Us</a></li>
    </ul>
  </div>
</nav>

<div id="lightbox_container"></div>

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

In JavaScript, the input box is set to automatically capitalize the first letter, but users have the ability

How can I automatically capitalize the first letter of a user's name input, but allow for overrides like in the case of names such as "de Salis"? I've read on Stack Overflow that CSS alone cannot achieve this with text-transform:capitalize;, so ...

I am interested in creating an HTML table using an array

My task is to populate a table with data from arrays containing id, name, and price values. However, something seems to be going wrong. Can you help me identify the issue? var data = {"id":["1986","1990","1989","1985","1988","1987"],"name":["name1","nam ...

Using two divs, each containing different content, with one incorporating a tinymce editor, in order

There are two div elements in my code: <div id="ing" style="position:relative;"> <div id="comm" style="position: absolute; width: 27% !important; height: 141px; right: 18px; top: 1px; "> </div> </div> After that, I set T ...

In Internet Explorer, the list items are overlapping, while functioning perfectly in all other web browsers

I've encountered a strange issue with my list item in Internet Explorer. Despite working perfectly in Chrome and other browsers, it fails to function properly in IE. I've built this application using the Vue framework and have faced various probl ...

Switching from Prototype to jQuery in ASP.NET is a smart move that will

Within the header section, the following code is present: <script language="javascript" type="text/javascript"> function setConBal() { conBal = 1; } function readBalance() { new Ajax.Updater('tableBalance', '_Bet/PanelBalance1 ...

Why is the renderer using viewport and scissor in Three.js resulting in a fully black canvas?

My user interface setup consists of two vertical windows - the left for the canvas and renderer, and the right for the UI components. Within this UI layout, I plan to include special viewers like a top view window. I have implemented the viewports and sc ...

The Server Discovery And Monitoring engine has been marked as obsolete

Currently, I am integrating Mongoose into my Node.js application with the following configuration: mongoose.connect(process.env.MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true, useFindAndModify: false }).then ...

Why does the sticky navbar not display anything on localhost:4200 in Angular, but works perfectly when placed in a regular HTML file?

I'm encountering an issue while trying to create a webpage in Angular 6. The content displays correctly when I write the code in NOTEPAD as normal HTML, but it doesn't work as expected when implemented in Angular. I am new to Angular and struggli ...

Retrieve the original jqXHR object from the success callback of the $.ajax function

My original task is as follows: Execute a jQuery.ajax() request. Upon success, perform additional checks on the data received from the server. If these checks fail, reject the promise for further handling. After researching extensively online, I came up ...

Is there a setting causing Webpack to not rebuild when there are changes to the CSS?

I have configured postcss-loader and style-loader on webpack, and I am using webpack-dev-server. However, every time I make changes to the CSS, webpack does not rebuild automatically. The script for webpack dev server that I use in npm scripts: webpack-d ...

What is the method for activating the open feature in react-dropzone-component by utilizing refs?

Currently, I am utilizing the react drop-zone component to facilitate file uploads to the server. My objective is to trigger the drop-zone open function upon clicking a button. Here is what I have experimented with so far: To reference the drop zone, I ...

Loop through the array to set the values of each item into the respective columns of the table using

As a newcomer to the world of javascript, I could really use some assistance with this particular issue. Let's start with a predefined table: <div id="SampleDiv"> <table id="SampleTable"> <tr> <td></td> ...

I am experiencing technical difficulties with my API resulting in a 500 Internal Server Error

My application involves managing products using CRUD operations. I am able to successfully make an HTTP request to the /api/deleteProduct route in order to delete a product based on its ID. However, the issue lies with creating a new product as the functi ...

While the Navbar component functions properly under regular circumstances, it experiences difficulties when used in conjunction with getStaticProps

https://i.stack.imgur.com/zmnYu.pngI have been facing an issue while trying to implement getstaticprops on my page. Whenever I try to include my navbar component, the console throws an error stating that the element type is invalid. Interestingly, I am abl ...

Set up a WhatsApp web bot on the Heroku platform

I am currently in the process of developing a WhatsApp bot using the node library whatsapp-web.js. Once I finish writing the script, it appears something like this (I have provided an overview of the original script) - index.js const {Client, LocalAuth, M ...

Modify the displayed image when hovering using inline coding techniques

I am having trouble changing an image on hover. I have attempted various methods without success. However, I need to stick with something similar to this code. Please let me know if there are any issues with this code. Thank you in advance. Code < ...

Encountering issues with accessing the clientWidth and clientHeight references of the DOM in Vue

Issue with 'clientWidth' and 'clientHeight' properties on Vue and Element types. <div class="invoice-step-detail" id="invoice" ref="invoice"> @Component({ name: 'CreateInvoice', co ...

Trigger an alert using the Ajax response

Is there a way to display the value of imageX outside of the $.ajax() function? var imageX; $.ajax({ type: 'GET', url: 'php/my1.php', dataType: 'json', async: 'false', success: function(response) ...

Tips for effectively handling repetitive bootstrap CSS code

As part of my coding routine, I often utilize the following code snippet to center specific content: <!-- horizontal --> <div class="d-flex align-items-center justify-content-center h-100"> .. </div> <!-- vertical --> & ...

Sending data from one HTML element to another using JQuery's Ajax function

I'm currently attempting to pass the value from an anchor tag into an ajax function. This is the HTML code I am working with <section> <div class="nav-section"> <nav> <ul> <li>< ...