How do I collapse the sidebar in mobile and tablet view using Bootstrap 4?

I am trying to create a collapsible sidebar that expands on large screens such as lg, but collapses with a visible button for tablet and mobile views (md or smaller).

How can I achieve this responsive behavior for my sidebar on mobile and tablet views? It should also display in expanded form on desktop views like lg and xl. Additionally, there should be a toggle button that is hidden on large desktop views but visible on small mobile and tablet views.

Do I need to implement custom JavaScript functionality for this?

I have referenced the Bootstrap 4 documentation on Collapse, but I am unsure how it can help me achieve the desired outcome (https://getbootstrap.com/docs/4.0/components/collapse/#options).

//Toggle Button
<h4 class="mb-3"><span class="text-muted">Search Filters</span>
    <button class="navbar-toggler border"
    type="button"
    data-toggle="collapse"
    data-target="#sidebar"
    aria-expanded="false"
    aria-label="Toggle filters">
      <span><i class="fas fa-filter"></i></span>
    </button>
 </h4>




//The Sidebar    
  <ul id="sidebar" class="list-group mb-3">
    <li class="list-group-item d-flex justify-content-between lh-condensed">
      <div>
        <h6 class="my-0">Header</h6>
        <div class="input-group mb-3">
          <ul>
            <li><input type="checkbox" aria-label="Checkbox"> Checkbox List Item </li>
            <li><input type="checkbox" aria-label="Checkbox"> Checkbox List Item </li>
            <li><input type="checkbox" aria-label="Checkbox"> Checkbox List Item </li>
            <li><input type="checkbox" aria-label="Checkbox"> Checkbox List Item </li>
            <li><input type="checkbox" aria-label="Checkbox"> Checkbox List Item </li>
          </ul>
        </div>
    </li>
    <li class="list-group-item d-flex justify-content-between lh-condensed">
      <div>
        <h6 class="my-0">Header</h6>
        <div class="input-group mb-3">
          <ul>
            <li><input type="checkbox" aria-label="Checkbox"> Checkbox List Item </li>
            <li><input type="checkbox" aria-label="Checkbox"> Checkbox List Item </li>
            <li><input type="checkbox" aria-label="Checkbox"> Checkbox List Item </li>
            <li><input type="checkbox" aria-label="Checkbox"> Checkbox List Item </li>
            <li><input type="checkbox" aria-label="Checkbox"> Checkbox List Item </li>
          </ul>
        </div>
    </li>
    <li class="list-group-item d-flex justify-content-between lh-condensed">
      <div>
        <h6 class="my-0">Header</h6>
        <div class="input-group mb-3">
          <ul>
            <li><input type="checkbox" aria-label="Checkbox"> Checkbox List Item </li>
            <li><input type="checkbox" aria-label="Checkbox"> Checkbox List Item </li>
            <li><input type="checkbox" aria-label="Checkbox"> Checkbox List Item </li>
            <li><input type="checkbox" aria-label="Checkbox"> Checkbox List Item </li>
            <li><input type="checkbox" aria-label="Checkbox"> Checkbox List Item </li>
          </ul>
        </div>
    </li>
  </ul>
  </div>

Answer №1

After seeking assistance from various other websites, I was able to find the solution. The individuals in the Slack Bootstrap Help Channel graciously directed me in the right direction by sharing a StackOverflow thread.

By utilizing that link in conjunction with the Collapse Documentation provided at Bootstrap, I successfully resolved the issue. Below is the code snippet...

// Used jQuery to implement the new logic:

  if ($(window).width() < 922) {
    $('#sidebar').collapse({
      toggle: false
    });
  } else {
    $('#sidebar').collapse({
      toggle: true
    });
  }


// Additionally, it was necessary to apply the .collapse class to the UL element:

  <ul id="sidebar" class="collapse list-group mb-3">
      ....
  </ul>

I trust this information will be beneficial to others!

Answer №2

Avoid the need for JavaScript by utilizing Bootstrap classes: https://getbootstrap.com/docs/4.1/utilities/display/#hiding-elements

Here's a way to achieve this:

//Button: Using the class d-lg-none will conceal the filters on large screens (visible only on xs-s-md sizes)

<h4 class="d-lg-none mb-3"><span class="text-muted">Search Filters</span>
 <button class="navbar-toggler border"
 type="button"
 data-toggle="collapse"
 data-target="#sidebar"
 aria-expanded="false"
 aria-label="Toggle filters">
  <span><i class="fas fa-filter"></i></span>
</button>
 </h4>


//Sidebar: "d-none d-lg-block" will only show the sidebar on large screens

  <ul id="sidebar" class="d-none d-lg-block list-group mb-3">
....
</ul>

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

Guide on creating a readUInt16BE function in a Node.js environment

Looking to implement the readUint16BE function in node.js, here's how it is declared: buf.readUInt16BE(offset, [noAssert]) Documentation: http://nodejs.org/api/buffer.html#buffer_buf_readuint16be_offset_noassert This function reads an unsigned 1 ...

Navigating Angular: Discovering Route Challenges in Less Than an Hour

Can someone take a look at my code and help me out? I'm trying to learn Angular.js by following the popular Angular.js in 60 minutes video tutorial, but it seems like things have been updated since then. I'm having trouble getting my routes to wo ...

Execute Python code alongside JavaScript functions using ExecJS - an efficient JavaScript engine for seamless integration with

Currently, I am exploring the integration of JavaScript engine with Python. I am interested in working with Python classes in JavaScript and vice versa, as well as using JavaScript code within Python. How can I achieve this? In a Java project, I have suc ...

Exploring Elasticsearch with Ajax Query Syntax

Attempting to send a post request via AJAX to my Elasticsearch index but encountering some issues. Here's the cURL result: [~]$ curl -XGET 'http://localhost:9200/firebase/_search?q=song:i%20am%20in' {"took":172,"timed_out":false,"_shards": ...

Having trouble rendering JSON data on a FlatList component in React Native

After expanding FlatList in console.log and verifying the JSON value, I am facing an issue where the values are not displaying on the list. The data is being passed to the second screen and displayed there, but the first screen remains blank. Any assistanc ...

The contrastText property of the MUI React Theme palette is not functioning properly

I am working with MUI React to design a menu and I have utilized the AppBar component. I would like to customize it in the following way: brown.myBrown = '#544846'; const brownTheme = createTheme({ palette: { primary: { ma ...

Fluctuating updated site (ajax)

What method do you recommend for maintaining the data in a table on a page current? Currently, I am using a timer that connects to the server via ajax every 2 seconds to check for updates. Is there a way to trigger an event or function only when the cont ...

In the Swiper function of JavaScript within a Django template, the occurrence of duplicate elements (products) is being generated

Experimenting with displaying products in a Django template, I decided to utilize the Swiper js class. This allowed me to showcase the products within a div, complete with navigation buttons for scrolling horizontally. However, when testing this setup wit ...

Encountering Angular Material UI issues following the transition from version 11 to 12

I am currently in the process of updating my Angular application from version 11 to 12, integrating Angular Material, and encountering some error messages: Error No.1 - Error NG8002: Cannot bind to 'ngModel' as it is not a recognized property of ...

What steps should I take to prevent my <mat-card> from expanding whenever messages are shown in Angular 9?

I have a <mat-card> containing a login form on my page. However, when error messages are displayed, the vertical size of the <mat-card> changes and I need it to remain the same. Is there a way to prevent this from happening? Below, you will ...

Handling errors within classes in JavaScript/TypeScript

Imagine having an interface structured as follows: class Something { constructor(things) { if (things) { doSomething(); } else return { errorCode: 1 } } } Does this code appear to be correct? When using TypeScript, I en ...

What is the explanation for the outcome "-9 >> 2 = -3"?

What is the reason behind 9 >> 2 = 2 compared to -9 >> 2 = -3 ? Wouldn't it make more sense for it to be -2 instead? ...

Unable to transfer data through Ionic popover

I've encountered an issue when trying to pass data to my popover component, as the data doesn't seem to be sent successfully. Code HTML <div class="message" id="conversation" *ngFor="let message of messages.notes"> <ion-row class= ...

Ways to reach the Document Object Model in a functional component

While working on a speedometer project in ReactJS with some vanilla syntax, I encountered an issue where the canvas element was returning null. Oddly enough, when running const canvas = document.getElementById('dial__container'); in the console, ...

What is causing the inefficacy of this particular SQL request method, while the alternative one proves effective?

It's surprising that the one not working is from the mssql package page. Why isn't it functioning on my machine? What am I missing here? The other example I found online works perfectly. On a side note - should these requests be done asynchronou ...

Placing a MongoDB query results in an increase of roughly 120MB in the total JS heap size

I'm puzzled by the fact that the heap size increases when I include a MongoDB database query in a function within my controller. Here is the code for my router: import { Router } from "express"; import profileController from '../contro ...

Using NextJS to navigate user journey by mapping an array of values from Formik to

I really appreciate all the help I've received so far, but I'm facing an issue trying to map an object with an array within it to the router. Here is my current code: const initialValues = { region: query.region || 'all', campt ...

Using onchange within an onchange event will not function as intended

When I am in the process of creating 2 dropdown menus filled from a database, the issue arises when the second dropdown is generated after selecting a value from the first one. Upon choosing an option from the second dropdown, my ajax function is triggered ...

Limiting the scope of the jQuery scrollToFixed functionality within various nested DIV elements

I have been grappling with this issue for the past two days without success. I am utilizing the ScrollToFixed plugin from https://github.com/bigspotteddog/ScrollToFixed and my goal is to restrict the fixed positioning within a parent DIV. Despite scouring ...

Creating a personalized image download feature in PhotoSwipe.js

I am currently working on a project that involves using the PhotoSwipe gallery. At line 175, there is code url:items[0].hqImage. I want to use the index of the current image instead of 0. How can I achieve this? I attempted to utilize the pswp.listen(&ap ...