Tips for implementing a collapsible sidebar within a single div element

Imagine a scenario where there is a div serving as a container for a sidebar on the left and main content on the right.

The goal is to create a collapsible sidebar navigation, allowing users to hide or display the sidebar with the click of a button.

Despite using Bootstrap 4, existing solutions found on the internet for this feature require extensive work. A simpler approach is sought after.

Here is the current code snippet:

<div class="container-fluid">
<div class="row">
    <div class="col-3 px-1 bg-dark" id="sticky-sidebar">
        <div class="py-2 sticky-top">
            <div class="nav flex-column">
                <a href="" class="nav-link">Sidebar</a>
                <a href="" class="nav-link">Link</a>
                <a href="" class="nav-link">Link</a>
                <a href="" class="nav-link">Link</a>
                <a href="" class="nav-link">Link</a>
                <a href="" class="nav-link">Link</a>
            </div>
        </div>
    </div>
    <div class="col" id="main">
        <h1>Main Area</h1>
        <p>Main content.</p>
    </div>
 </div>
</div>

The div structure is already split into two blocks, as shown in this codeply:

https://i.sstatic.net/bL7Q4.jpg

How can the sidebar within the div be made collapsible?

Appreciate any assistance provided. Thank you.

Answer №1

If you want to create a collapsible sidebar, you can achieve it by wrapping the content in a div with an id and specific classes like navbar-collapse and collapse. Here's how you can do it:

<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbar" aria-controls="navbar" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbar">
  <div class="nav flex-column">
    <a href="" class="nav-link">Sidebar</a>
    <a href="" class="nav-link">Link</a>
    <a href="" class="nav-link">Link</a>
    <a href="" class="nav-link">Link</a>
    <a href="" class="nav-link">Link</a>
    <a href="" class="nav-link">Link</a>
  </div>
</div>

If you need to animate the sidebar off the side, you can use some JavaScript to toggle the visibility. Here's an example:

$('.navbar-toggler').on('click', function(e) {
  e.preventDefault();
  var target = $(this).data('target');
  $(target).toggleClass('hide') ;
});
#sticky-sidebar {
  min-height: 100vh;
  transition: max-width 1s;
  overflow:hidden;
}
#sticky-sidebar.hide {
  max-width:0;
  padding:0 !important;
}
.navbar-toggler {
  background-color: #000000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container-fluid">
  <div class="row">
    <div class="col-3 px-1 bg-dark" id="sticky-sidebar">
      <div class="py-2 sticky-top">
          <div class="nav flex-column">
            <a href="" class="nav-link">Sidebar</a>
            <a href="" class="nav-link">Link</a>
            <a href="" class="nav-link">Link</a>
            <a href="" class="nav-link">Link</a>
            <a href="" class="nav-link">Link</a>
            <a href="" class="nav-link">Link</a>
          </div>
        </div>
    </div>
    <div class="col" id="main">
      
        <button class="navbar-toggler" type="button" data-target="#sticky-sidebar" aria-controls="navbar" aria-expanded="false" aria-label="Toggle navigation">
          <span class="navbar-toggler-icon"></span>
        </button>
      <h1>Main Area</h1>
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras placerat, eros nec viverra eleifend, lacus nunc lacinia dolor, et varius velit turpis a mauris. Nulla dictum semper ipsum, sed interdum urna condimentum ac. Etiam interdum, enim sit amet ultrices lacinia, nulla erat pretium tellus, ut elementum justo mauris nec orci. Sed at ipsum libero. Morbi eleifend, sapien vitae consectetur auctor, justo dolor varius dolor, sed ultricies sapien dui ut turpis. Vestibulum leo libero, varius eu interdum quis, posuere in orci. Fusce vitae tellus et dui scelerisque viverra ut vel ipsum. Integer placerat elit eu egestas ultricies. Sed tincidunt nunc in eros dapibus, in mollis odio venenatis. Nam sagittis, purus nec molestie pellentesque, libero libero tincidunt eros, sit amet tincidunt mi dolor vel elit. Vestibulum id facilisis dui. Cras dignissim quam non dolor sagittis vulputate. Praesent vestibulum pellentesque mauris, in auctor nisi tempor et. Etiam odio orci, faucibus a eros ut, aliquam ullamcorper sapien. Nulla consectetur, sapien vitae dapibus auctor, mi lacus malesuada metus, ut iaculis massa nulla vel mi. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vivamus dictum lectus neque, sit amet condimentum purus commodo sit amet. Vivamus scelerisque ligula id lacinia feugiat. Cras tincidunt id massa eu maximus. Vestibulum ac arcu at erat volutpat suscipit. Aliquam erat volutpat...
    </div>
  </div>
</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

button to dim the image collection

On the top right corner of my image gallery, there's a button that, when clicked, creates an overlay darkening the image. I'm trying to figure out how to toggle this effect on and off with a click. Any suggestions on how I can achieve this? Here ...

What is the best way to play a random song when the user clicks a button?

My goal is to develop a website where users can click on an image and have a random song play from a playlist. I currently have a functioning code that activates one song, but it fails when adding multiple songs to the mix. <html> <head> ...

The Radio button and Checkbox values are causing an issue where the Radio button is continuously summing upon clicking without a limit. Why is this happening? Check out

I'm currently stuck in a function and believe it would be helpful for you to guide me along the correct path. My goal is to sum the values of checked boxes with the values of checked radio buttons. However, the radio values are continuously accumulat ...

scraping text content from a CSS node using Scrapy

My goal is to extract a catalog ID number from the following webpage: from scraping.selector import Selector from scraping.http import HtmlResponse url = 'http://www.enciclovida.mx/busquedas/resultados?utf8=%E2%9C%93&busqueda=basica&id=& ...

What could be causing my jQuery handler to not capture my form submission?

I am developing a Ruby web application and using JQuery and AJAX to send/receive data. However, I am facing an issue where pressing the enter key does not submit the form. What should I do to ensure that my form submits successfully? Within my Foundation ...

Generate numerous lines of div elements

I am looking to set up a 2x2 layout with 4 div elements. Check out my experiment in this fiddle where I utilized inline-block for display. My goal is to position "div 3" and "div 4" directly beneath 1 and 2, respectively. Is there a way to achieve this wit ...

The navigation bar options are not collapsing as intended

When I resize my page to width:750px;, my navigation bar is not collapsing the items. Despite trying to edit my CSS, I am still clueless. Here is my live page. This is the CSS for my slidebar: @media (max-width: 480px) { /* Slidebar width on extra small ...

Tips for effectively combining an array with jQuery.val

My goal is to have multiple form fields on a page, gather the input results into an array, and then store them in a database. This process was successful for me initially. However, when I introduced an autocomplete function which retrieves suggestions from ...

Changing the height of a Bootstrap 3 row without using less variables

Can someone please explain how to adjust the .row width in Bootstrap so that the col grid still functions correctly, but certain .rows are tighter than default? Thank you. ...

Selecting objects within a small three.js view

I am able to showcase an entire page filled with graphical elements using three.js and can even select objects by clicking on them. However, when attempting to display three.js graphics in a small viewport within an HTML page, issues arise. In order to ca ...

Mastering the alignment of elements in HTML, CSS, and Bootstrap

Currently, I am utilizing Thymeleaf, Bootstrap, and CSS for the front-end view of my project. I am encountering an issue where I am unable to align the button and the level as displayed in the provided image: https://i.sstatic.net/8RoPi.png Update: Below ...

Transform HTML into a Word document format

When using word automation to generate a word document, how can I convert HTML tags to the word document format while preserving styles such as font, bold, tables, and other elements? ...

How to Conceal Axis Label in an HTML5 Canvas Line Chart

Is there a way to hide the x-axis label from a line chart without hiding the y-axis label as well? I tried using scaleFontSize: 0,, but that ended up hiding both axis labels. I only want to hide the x-axis label. var lineOptions = { ///Boo ...

What is the best way to target an input element with a specific ID using JQuery Mobile?

For instance, <input type="button" id="one" value="o" data-role="button" data-inline="true" class="game"/> I aim to utilize this button in a manner where I can access its value using the ID, like for updating the value. Is there a way to reference ...

Leveraging the combination of <Form>, jQuery, Sequelize, and SQL for authentication and navigation tasks

My objective is to extract the values from the IDs #username-l and #pwd-l in an HTML form upon the user clicking the submit button. I aim to compare these values with those stored in a SQL database, and if they match exactly, redirect the user to a specifi ...

How to identify an element based on the text content of the element that follows it using XPath

I am working with this specific piece of HTML code <div class="a-expander-content a-spacing-base a-expander-inline-content a-expander-inner a-expander-content-expanded" style="" aria-expanded="true"> <form id="pp-yT-23" class="pmts-add-cr ...

JQuery mishandles its left positioning

Here's the code snippet I've been working with: $(this).closest("p").after('<strong>' + arMess[iCurIndex] + '</strong>').next().animate({ top: $(this).offset().top - 57, left: -$(this).widt ...

Leveraging icons with Bootstrap 4.5

I am currently exploring how to incorporate Bootstrap 4.5 icons using CSS. Do you have any examples of code that could guide me on how to achieve this? I am specifically interested in understanding the required CSS declarations that would allow me to use t ...

What could be causing the HTML page to not interpret the PHP page properly?

Whenever I click on the submit button, nothing happens and my data is not inserted into the database. I'm in the process of creating a registration page (register2.html) and db_reg.php to manage database entry. However, it seems that the HTML page i ...

Delete items within the first 10 minutes of shutting it down

Is there a way to temporarily remove a newsletter element for 10 minutes after closing it on a webpage? The idea is that once the panel is closed, it should stay hidden even if the page is refreshed within that timeframe. I was considering using local stor ...