Troubleshooting Navigation Bar Toggle Button Issue in Bootstrap 5

Currently, I am in the process of working on a web project that requires the implementation of a responsive sidebar. This sidebar should be toggleable using a button located in the navigation bar.

My choice for the layout is Bootstrap, and I have come across some challenges when trying to achieve this specific functionality. The goal is to have the sidebar hidden by default on mobile devices and only become visible when the user interacts with the menu button in the navbar. On larger screens, the sidebar should remain visible without any additional action required from the user. To address these requirements, I attempted to use CSS media queries to manage the visibility of the sidebar based on screen size. Additionally, I used JavaScript to create a function that toggles the sidebar when the menu icon in the navbar is clicked. However, upon testing, I noticed that clicking on the menu icon does not display the sidebar as intended.

If anyone could provide me with guidance on how to correctly implement this responsive sidebar feature while using Bootstrap 5, it would be greatly appreciated.

Answer №1

  1. I decided to enhance the functionality of the navbar by adding an additional button, alongside the existing navbar-toggler, that allows for manipulation of the sidebar on mobile devices. This new button incorporates the

    onclick="toggleSidebar()"
    function.

  2. To facilitate the styling and display of elements, I created two classes in the CSS file: show and hide.

  3. The d-lg-block class was removed from the sidebar element to streamline its layout.

  4. An id="sidebar" attribute was added to the sidebar element to enable easy identification through ID referencing.

  5. Within the toggleSidebar function, toggling between displaying and hiding the sidebar is achieved by switching between the show and hide classes in the classList respectively.

For a detailed view of the updated code, refer to the snippet provided below:

function toggleSidebar() {
  let sidebar = document.getElementById("sidebar");
  if (sidebar.classList.contains('show')) {
    sidebar.classList.remove('show');
    sidebar.classList.add('hide');
    console.log('show')
  } else {
    sidebar.classList.add('show');
    sidebar.classList.remove('hide');
    console.log('hide')
  }
}
.sidebar {
  min-height: calc(100vh - 56px);
  width: 240px; 
}

.show {
  display: inline !important;
}

.hide {
  display: none !important;
}

@media (max-width: 767.98px) {
  .sidebar {
    display: none;
  }
}

@media (min-width: 768px) {
  .sidebar {
    position: fixed;
    top: 56px;
    bottom: 0;
    left: 0;
    z-index: 100;
    padding: 20px 0;
    overflow-x: hidden;
    overflow-y: auto;
    border-right: 1px solid #e7e7e7;
  }
}
<!-- Navbar -->
<nav class="navbar navbar-expand-lg navbar-light bg-light">
  <div class="container-fluid">
    <a class="navbar-brand" href="#">Logo</a>
    <button class="navbar-toggler" type="button" 
      data-bs-toggle="collapse" data-bs-target="#navbarNav" 
      aria-controls="navbarNav" 
      aria-expanded="false" 
      aria-label="Toggle navigation" >
      <span class="navbar-toggler-icon"></span>
    </button>
    
    <button class="btn btn-white shadow" onclick="toggleSidebar()">
       <span class="navbar-toggler-icon"></span> Change
    </button>
  </div>
</nav>

<!-- Sidebar -->
<div class=" bg-light sidebar show" id="sidebar">
  <a href="#" class="d-block p-3 link-dark text-decoration-none" aria-label="Sidebar">
    <span class="fs-5">Sidebar</span>
  </a>
  <ul class="nav nav-pills flex-column mb-auto">
    <li class="nav-item">
      <a href="#" class="nav-link" aria-current="page">Dashboard</a>
    </li>
    <li class="nav-item">
      <a href="#" class="nav-link link-dark">Orders</a>
    </li>
    <li class="nav-item">
      <a href="#" class="nav-link link-dark">Products</a>
    </li>
    <li class="nav-item">
      <a href="#" class="nav-link link-dark">Customers</a>
    </li>
  </ul>
</div>

<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="791b16160d0a0d0b1809394c5749574b">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

<!-- Content Area -->
<div class="container-fluid main-content">
  <div class="row">
    <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4">
      <div class="pt-3 pb-2 mb-3 border-bottom">
        <h1 class="h2">Content Area</h1>
      </div>
      <h4>Main</h4>
    </main>
  </div>
</div>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="06646969727572746776463328362834">[email protected]</a>/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>

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

Angular JS sending a message to various views, including a pop-up modal

One of the services I have created is designed to manage message broadcasting to controllers that require it. The service implementation: .factory('mySharedService', function($rootScope) { var sharedService = {}; sharedService.message = &a ...

Playing out the REST endpoint in ExpressJS simulation

Suppose I have set up the following endpoints in my ExpressJS configuration file server.js: // Generic app.post('/mycontext/:_version/:_controller/:_file', (req, res) => { const {_version,_controller,_file} = req.params; const ...

executing a Prisma database migration with various schemas

I am currently immersed in a Prisma project where my goal is to create a node module that can be utilized by other projects. The challenge now is to ensure that the database stays synchronized with the models and the primary project, so all testing platfor ...

How can I stop a user from navigating through links or submitting forms using jQuery?

I'm exploring the idea of converting my website into a Single Page Application. One challenge I am facing is capturing the navigation process, for example: <a href="myData.php">Change My Data</a> When a user clicks on the "Change My Data ...

The submitHandler for AJAX does not function properly when using bootstrapvalidator

I'm encountering an issue with the Bootstrap validation tool found at https://github.com/nghuuphuoc/bootstrapvalidator The submitHandler function seems to be malfunctioning for me. Upon form submission, the entry is not being created and the form rel ...

The table headers in the second table do not match the queryAllSelector

I've encountered an issue with my JavaScript snippet that displays a responsive table. When I use the snippet for a second table with the same class, the formatting gets messed up on mobile devices (try resizing your screen to see). It seems like the ...

In Safari, the CSS filter value may not be applied immediately, whereas in Chrome it is

While dragging the input range, the brightness value (also a CSS property) updates but the image is not instantly affected in Safari. (It works well in Chrome) How can the changes be applied to the image while dragging? var app = Vue.createApp({ data() ...

Conflict in Vue.js between using the v-html directive and a function

Below is the component template for a notification: <template> <div> <li class="g-line-height-1_2"> <router-link :to="linkFromNotification(item)" @click.native="readNotification(item)" v-html="item. ...

Develop a PDF generator in ReactJS that allows users to specify the desired file name

Is there a way to customize the file name of a generated PDF using "@react-pdf/renderer": "^2.3.0"? Currently, when I download a PDF using the toolbar, it saves with a UID as the file name (e.g., "f983dad0-eb2c-480b-b3e9-574d71ab1 ...

Showing content based on the route - Angular

I'm struggling to hide the navbar based on a specific route in my application. I have managed to subscribe to the route changes, but I am having difficulty changing the display property accordingly. Here is what I have so far: export class AppCompo ...

Displaying content generated by Html.Raw in MVC4 using JavaScript and AJAX is causing displacement of content within the <a> tags in the HTML

My project includes a feature where emails sent to a specific address are parsed, with attachments saved to the network and metadata stored in a database. If the serial number of a finished good matches the one included in the email, a note is generated an ...

Incorporating a full-page background into a specific view using AngularJS

In order to implement a fullscreen CSS background for a specific view in my app, I attempted adding a class to the body. However, this approach caused the background to persist in the cache and remain visible when switching views. The challenge arises fro ...

Why won't my AngularJS checkbox stay checked?

In my application, I have the following code: <input type="checkbox" ng-checked="vm.eduToEdit.test" /> {{vm.eduToEdit.test}} <input type="checkbox" ng-model="vm.eduToEdit.test"> The value of vm.eduToEdit.test is displaying t ...

What causes the findByIDAndUpdate method to return a `null` value in Mongoose 6?

I am working with nodejs v18, Express v4, and Mongoose v6. I am attempting to update a document, but when using the line below, it returns null. const doc = await User.findByIdAndUpdate(userId, newUser, { new: true }) // doc is null The object newUser con ...

Create a placeholder for the module function

Update: Providing more specific details. Our team has developed a Github API wrapper extension and we are looking to test different use cases for it. However, we prefer not to use the API wrapper extension directly during testing and instead want to stub ...

hashSync function needs both data and salt to generate the hash

I can't figure out why I am encountering this issue, I have checked the documentation and couldn't find my mistake. Any suggestions? Error: data and salt arguments required const {create} = require('./user.service'); const {genSaltS ...

Refreshing jQuery via Ajax Response

In our JSF2 application, we encounter situations where we need to re-invoke the JavaScript (specifically jQuery for UI styling) when making Ajax calls. However, it seems that the JavaScript functions are not being called upon receiving the Ajax response fr ...

Issue with parsing JSONP using jQuery's AJAX request

I am encountering an issue with a jQuery ajax request that I have set up. Here is the code: jQuery.ajax({ url: serverAddress+'php/product.php', type: 'GET', jsonpCallback: "callback7", dataType: 'jsonp', d ...

Difficulty in accessing JSON data with Node.js

Encountering difficulties with retrieving JSON data from a JSON file, I am faced with the following error message: "NetworkError: 404 Not Found - http://localhost:8000/channels.json" Below is the code snippet used to fetch JSON data in my HTML file: ...

Issue with Promise.all not waiting for Promise to resolve

After making a request to the server, I receive the data as a promise, which contains the correct information. However, for some reason, the program fails to execute properly. Prior to uploading it on Zeit, this program was functioning correctly. Fetch R ...