Question about Bootstrap sidebar

I found this cool tutorial for sidebars using bootstrap with toggle button that shows and hides sidebar, its on this site a very first static sidebar tutorial https://bootstrapious.com/p/bootstrap-sidebar. However, following the codes i understood most of stuff. But one thing i dont understand is in Media queries when browser gets resized to mobile width (max-width: 768px) why did he use .active class to set sidebar’s left margin to 0? I understand why margin was set like that and what he was targeting, but without using active class it wouldnt work at all, i tried it. Only by using along with id sidebar class of active it works. It confuses me.
Here’s HTML :

<!doctype html>
<html>
    <head>
        <meta charset="utf-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Test Page</title>
        <link href="https://fonts.googleapis.com/css?family=Lato:400,700" rel="stylesheet">
        <!--<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">-->
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
        <link rel="stylesheet" type="text/css" media="screen" href="Testing.css">
    </head>

    <body>
      
        <div class="wrapper">
            
            <nav id="sidebar">
                <div class="sidebar-header">
                    <h3>Bootstrap Sidebar</h3>
                </div>

                <ul class="list-unstyled components">
                    <p>Dummy Heading</p>
                    <li class="active">
                       <a href="#homeSubmenu" data-toggle="collapse" aria-expanded="false" class="dropdown-toggle">Home</a>
                       <ul class="collapse list-unstyled" id="homeSubmenu">
                           <li>
                               <a href="#">Home 1</a>
                           </li>
                           <li>
                               <a href="#">Home 2</a>
                           </li>
                           <li>
                               <a href="#">Home 3</a>
                           </li>
                       </ul>
                    </li>
                    <li>
                        <a href="#">About</a>
                    </li>
                    <li>
                        <a href="#pageSubmenu" data-toggle="collapse" aria-expanded="false" class="dropdown-toggle">Pages</a>
                        <ul class="collapse list-unstyled" id="pageSubmenu">
                            <li>
                                <a href="#">Page 1</a>
                            </li>
                            <li>
                                <a href="#">Page 2</a>
                            </li>
                            <li>
                                <a href="#">Page 3</a>
                            </li>
                        </ul>
                    </li>
                    <li>
                        <a href="#">Portfolio</a>
                    </li>
                    <li>
                        <a href="#">Contact</a>
                    </li>
                </ul>
           </nav>

            <div id="content">
                <nav class="navbar navbar-expand-lg navbar-light bg-light">
                    <div class="container-fluid">
                        
                        <button type="button" id="sidebarCollapse" class="btn btn-info">
                            <i class="fas fa-align-left"></i>
                            <span>Toggle Sidebar</span>
                        </button>
                    </div>
                </nav>
            </div>
        </div>
       
       
       
       
        

    <script defer src="https://use.fontawesome.com/releases/v5.0.6/js/all.js"></script>
    <!--<script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>-->
    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
    </body>
</html>

CSS:

body {
    font-family: 'Poppins', sans-serif;
    background: #fafafa;
}

p {
    font-family: 'Poppins', sans-serif;
    font-size: 1.1em;
    font-weight: 300;
    line-height: 1.7em;
    color: #999;
}

a, a:hover, a:focus {
    color: inherit;
    text-decoration: none;
    
}

.wrapper {
    display: flex;
    width: 100%;
    align-items: stretch;
}

#sidebar {
    min-width: 250px;
    max-width: 250px;
    min-height: 100vh;
    background: #7386D5;
    color: #fff;
    transition: all 0.3s;
}

#sidebar .sidebar-header {
    padding: 20px;
    background: #6d7fcc;
}

#sidebar ul.components {
    padding: 20px 0;
    border-bottom: 1px solid #47748b;
}

#sidebar ul p {
    color: #fff;
    padding: 10px;
}

#sidebar ul li a {
    padding: 10px;
    font-size: 1.1em;
    display: block;
}

#sidebar ul li a:hover {
    color: #7386D5;
    background: #fff;
}

#sidebar ul li.active > a, a[aria-expanded="true"] {
    color: #fff;
    background: #6d7fcc;
}

ul ul a {
    font-size: 0.9em !important;
    padding-left: 30px !important;
    background: #6d7fcc;
}



a[data-toggle="collapse"] {
    position: relative;
}

.dropdown-toggle::after {
    display: block;
    position: absolute;
    top: 50%;
    right: 20px;
    
}

@media (max-width: 768px) {
    #sidebar {
        margin-left: -250px;
    }

    #sidebar .active {
        margin-left: 0;
    }
}

JavaScript (it doesnt work for some reason, its in JS file):

$(document).ready(function () {

    $('#sidebarCollapse').on('click', function () {
        $('#sidebar').toggleClass('active');
    });
});

So by setting it to zero, they are forcing it to show on mobile despite the fact it is default hidden on mobile. So if you look shrink your browser, by default the menu disappears but if you click the button, active gets added as a class and it overrides the -250 and brings the menu back on the screen.

1 Like

But i dont get it why did he had to use .active class since its only used with <li> element?

The active class is forced on the code when the javascript is toggled. So the javascript actually removes the class, effectively disabling the CSS when the menu is hidden. He forces the menu to hide with the -250 and if you use the toggle button, it forces it override the -250 with a 0, showing the menu on mobile. The Javascript adds the active class back and the CSS kicks back in.

So active class he added is in fact not the one he used in list element? Is it part of boostrap maybe?

No it’s not part of Bootstrap. It’s defined in the media query. Basically the only way to turn off CSS is to remove the class. He is removing the active class from the html using javascript when a person hits the toggle button. When a person hits the button again it adds the active class back, effectively turning the CSS back on.

It is the same class but he’s redefining it using the media query.

Check out his demo page, and inspect the menu (right click on menu and inspect element), you should see the active class. Click the toggle and and inspect again, the active class should be gone. Turn the menu back on and resized your browser window, the menu should disappear. Click the button and the menu appears. If you inspect the menu you should find the active class added back in.

Media queries are only activated when the parameters are met (in this case screen size), but he’s using them to give the menu a different behavior on mobile. Active is default on desktop but on mobile it is not. Javascript can remove and add CSS on the fly.

Im understanding your explanation of what active does, but im wondering what is active class? Where did it come from? Part that is confusing me is active class in his li element. Im talking about this:

<ul class="list-unstyled components">
                   <p>Dummy Heading</p>
                   <li class="active">
                      <a href="#homeSubmenu" data-toggle="collapse" aria-expanded="false" class="dropdown-toggle">Home</a>
                      <ul class="collapse list-unstyled" id="homeSubmenu">
                          <li>
                              <a href="#">Home 1</a>
                          </li>
                          <li>
                              <a href="#">Home 2</a>
                          </li>
                          <li>
                              <a href="#">Home 3</a>
                          </li>

etc etc...
  

See this <li class="active">??? It apparently has nothing to do with that class since i tested it without it and it still works. His active class he used in media query had to come from somewhere. Unless active class specificed where he currently is at on page, in this case he’s on Home page, so does it mean that active class he used actually triggers the nav bar with page he’s currently on? It might sound confusing to you but active class had to come from somewhere.

EDIT: I looked carefuly around code on inspect element and class of active shows up in his <nav id="sidebar" class> Still confused how it got there.

It got in id=“sidebar” because of Javascript.

The active class is defined here:

#sidebar ul li.active > a, a[aria-expanded="true"] {
    color: #fff;
    background: #6d7fcc;
}

And here in the media query:

 #sidebar .active {
        margin-left: 0;
    }

But this:

$(document).ready(function () {

    $('#sidebarCollapse').on('click', function () {
        $('#sidebar').toggleClass('active');
    });
});

Adds and removes the active class. This controls the toggle button. It deletes active from the HTML and put it back in. The HTML refreshes when the button is clicked and if it sees active in the html, it applies it. If it does not it does not apply that CSS. This code, that seems to do nothing adds and removes active from the code.

The media query gives an additional area of functionality telling the CSS only to apply active css in the sidebar ID when the screen is that small.

HTML only gives the page structure to the browser and creates items that can be grabbed by other languages. CSS, as you know, styles the page. It’s mostly passive, meaning that it happens regardless. Unless you uses Media queries, which put some parameters on when CSS can happen, in this case when the screen is below a certain size. Active is defined in the CSS.

Javascipt gives you the ability to manipulate the code directly in the DOM. So let’s take a look at what it does. Note this is a Jquery Framework, so it’s a bit different than plain JavaScript.

$(document).ready(function () {

    $('#sidebarCollapse').on('click', function () {
        $('#sidebar').toggleClass('active');
    });
});

So when the toggle button, with an Id of sidebarCollapse is click, the function looks for the sidebar ID and adds a class of active. If the class is there, it removes it. When it’s there the in the HTML the browser applies the CSS, when it’s not in the HTML…it does not apply the CSS.

So by clicking this:

<button type="button" id="sidebarCollapse" class="btn btn-info">

you activate the JavaScript becuase the ID matches what it’s looking for to add and remove active.

1 Like

Ok i just tested it by giving it a different class name instead of active and it still works. So apparently its to do with script adding and removing class only if its styled in CSS so browser basically adds it to given id or class in this case he chose id of sidebar while giving it a random class to be triggered with a button. I understand it completely now, i even looked up one simple tutorial and that guy used the same trick with JS. I guess we learn something new every day. Thanks for your explanation, sorry if i confused you in any way.