9

I wish to create a collapsible sidebar that the user can toggle. After much playing, I have achieved it, but right now, it is very ugly. Here's the code:

<div class="container-fluid">
  <div class="row">
    <nav class="col-md-3 collapse show" id="sidebar">
      <h2>I'm a sidebar</h2>      
    </nav>
    <main class="col-md-9">
      <i class="fa fa-times" data-toggle="collapse" data-target="#sidebar" aria-hidden="true" aria-expanded="false" aria-controls="sidebar"></i>
      <h2>I'm the main content</h2>
    </main>
  </div>
</div>

The issue with this is, the collapsing is vertical, and then once collapse, the content doesn't go full width!

Avi Turner
  • 10,234
  • 7
  • 48
  • 75
J86
  • 14,345
  • 47
  • 130
  • 228

1 Answers1

5

There is an easy way, you do not need to use jQuery. Look at this example:

<div class="container-fluid">
  <div class="row">
    <nav class="col-md-3 collapse show" id="sidebar">
      <h2>I'm a sidebar</h2>      
    </nav>
    <main class="col-md-9">
      <i class="fa fa-times" data-toggle="collapse" data-target="sidebar" aria-hidden="true" aria-expanded="false" aria-controls="sidebar" onclick="document.getElementById(this.getAttribute('data-target')).style.display = 'none';"></i>
      <h2>I'm the main content</h2>
    </main>
  </div>
</div>

I've changed data-target and added a very simple onclick.

EDIT:

Further improvements:

<div class="container-fluid">
  <div class="row d-flex">
    <nav class="col-md-3 collapse show width" id="sidebar">
      <h2>I'm a sidebar</h2>      
    </nav>
    <main class="col-md-9">
      <i class="fa fa-times" data-toggle="collapse" data-target="#sidebar" aria-hidden="true" aria-expanded="false" aria-controls="sidebar" onclick="var that = this; setTimeout(function() {console.log(that.parentNode);that.parentNode.style.flex = 'auto';that.parentNode.style['max-width'] = 'none';}, 2000);"></i>
      <h2>I'm the main content</h2>
    </main>
  </div>
</div>
Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175
  • Thanks @Lajos, see updated Q. I managed to get it working, but not the nice way – J86 Oct 04 '17 at 11:52
  • How can i get the sidebar to be scrollable? Both horizontally and vertically? Thanks! – NacDan Dec 02 '19 at 04:46
  • @NacDan you can achieve that using CSS, please take a look at overflow-x and overflow-y CSS properties for the div you intend to make scrollable. – Lajos Arpad Dec 02 '19 at 10:55