Ways to conceal sidebar after user logs out and reveal sidebar upon user's successful login?

Currently, I am utilizing the Dashgum bootstrap template obtained from Gridgum for a specific assignment. The task involves displaying the side navbar for logged-in users persistently, even after they have closed the site, and hiding the side navbar completely for users who are logged out.

Although the side navbar is initially visible by default, I intend to set its default state to "hidden". How can I achieve the initial hiding of the side navbar?

Being relatively new to bootstrap, I am still acquainting myself with it. I am reaching out on SO as a final resort for assistance.

HTML Code for the Side Navbar

<aside>
          <div id="sidebar"  class="nav-collapse ">
              <!-- sidebar menu start-->
              <ul class="sidebar-menu" id="nav-accordion">

                  <p class="centered"><a href="profile.html"><img src="assets/img/ui-sam.jpg" class="img-circle" width="60"></a></p>
                  <h5 class="centered">Marcel Newman</h5>

                  <li class="mt">
                      <a href="index.html">
                          <i class="fa fa-dashboard"></i>
                          <span>Dashboard</span>
                      </a>
                  </li>
</ul>
          </div>
      </aside>

JS Code for Sidebar Collapse

//    sidebar toggle

    $(function() {
        function responsiveView() {
            var wSize = $(window).width();
            if (wSize <= 768) {
                $('#container').addClass('sidebar-close');
                $('#sidebar > ul').hide();
            }

            if (wSize > 768) {
                $('#container').removeClass('sidebar-close');
                $('#sidebar > ul').show();
            }
        }
        $(window).on('load', responsiveView);
        $(window).on('resize', responsiveView);
    });

    $('.fa-bars').click(function () {
        if ($('#sidebar > ul').is(":visible") === true) {
            $('#main-content').css({
                'margin-left': '0px'
            });
            $('#sidebar').css({
                'margin-left': '-210px'
            });
            $('#sidebar > ul').hide();
            $("#container").addClass("sidebar-closed");
        } else {
            $('#main-content').css({
                'margin-left': '210px'
            });
            $('#sidebar > ul').show();
            $('#sidebar').css({
                'margin-left': '0'
            });
            $("#container").removeClass("sidebar-closed");
        }
    });

Although I attempted CSS modifications and executed the jQuery command

$("#container").addClass("sidebar-closed");

I embedded the HTML page with the mentioned JavaScript tag following the CSS, yet the navbar continues to display by default.

EDIT 1 - I have revised the problem's premise to offer additional context.

  • I appreciate everyone's responses to my query and experimented with all the solutions provided. However, the issue I encountered was the table and the side navbar overlapping (for logged-in users), and upon logout, the side navbar hides, but the main content does not shift left.

EDIT 2 - Due to the overlapping of the table and the side navbar, I have decided to conceal the navbar by default, but my attempts thus far have been unfruitful.

Answer №1

It seems like you were so close!

The toggle function in their code adds and removes the class sidebar-close based on the window size.

You used

$("#container").addClass("sidebar-closed");

Try replacing the class sidebar-closed with sidebar-close like this:

$("#container").addClass("sidebar-close");


Answer №2

To ensure your code runs smoothly without any delay, include the following lines in your JavaScript file if you do not currently have a document.ready function:

$(document).ready(function(){
         $('#main-content').css({
                    'margin-left': '0px'
                });
                $('#sidebar').css({
                    'margin-left': '-210px'
                });
                $('#sidebar > ul').hide();
    }

If you already have a document.ready function in your script, simply add the code below inside it:

$('#main-content').css({
            'margin-left': '0px'
        });
        $('#sidebar').css({
            'margin-left': '-210px'
        });
        $('#sidebar > ul').hide();

Implementing these changes should help optimize your code.

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

What is the best way to acquire the href value from this source?

Looking to extract the dynamic value "3 Sent" from the html snippet provided. How can this be achieved? <ul class="nav nav-tabs some-tabs"> <li class="active"> <a href="#accepted" data-toggle="tab">1 Accepted</ ...

The color is missing in the custom button of Bootstrap v5.2

Trying to incorporate a unique button class in Bootstrap with an iris-purple color. Utilized Sass for creating the custom button: @import "../node_modules/bootstrap/scss/bootstrap"; $mynewcolor:#5D3FD3; .btn-purple { @include button-variant( ...

The toolbar button in the Froala WYSIWYG editor is mysteriously missing from view

Embarking on a project with Froala editor and Angular 1, I meticulously followed the documentation to show the insertImage button and insertTable, but they are not appearing. Here is my code: var tb = ["bold", "italic", "insertTable", "insertImage"]; $sc ...

Verify and generate a notification if the value is null

Before saving, it is important to check for any null values and alert them. I have attempted to do so with the following code, but instead of alerting the null values, the data is being saved. . function fn_publish() { var SessionNames = getParamet ...

"Step-by-step guide on implementing a click event within a CellRenderer in Angular's Ag-Grid

paste your code hereI'm currently working on implementing edit and delete buttons within the same column for each row using Angular ag-Grid. To visually represent these buttons, I am utilizing icons. While I have successfully displayed the edit and de ...

How can you create a unique record by appending a number in Javascript?

Currently, when a file already exists, I add a timestamp prefix to the filename to ensure it is unique. However, instead of using timestamps, I would like to use an ordinal suffix or simply append a number to the filename. I am considering adding an incr ...

Translate CSS into JavaScript while maintaining selector understanding

I am interested in developing a tool that can read a .css file and generate a function that will accept an array of class names as input and output the corresponding styles for an element with those classes, represented as a JavaScript object. This tool wo ...

Links arranged in semicircles along the perimeter of the page

Here is some code that I have created to display two links in circles positioned on the left and right sides of a webpage. [class*="navigation"] .nav-previous, [class*="navigation"] .nav-next { position: fixed; z-index: 999; top: 50%; text-align ...

There is an error message in Vue nextTick: "TypeError: this.method is not a function." The error only appears in my console, but the functionality seems to be working correctly in the browser

I'm experiencing an issue where I encounter an error when accessing a certain component for the second time in my browser. The strange thing is that everything appears to be working fine initially, but the error occurs when I try to perform actions li ...

Executing a function every time a prop is updated within the component

I have a prop named transcript in one of my components. Whenever I speak a voice intent, it gets updated. I want to execute a function every time the transcript changes and pass the transcript as an argument. In this code snippet, I attempted to use an On ...

Hover effects in CSS animations can be hit or miss, with some working smoothly while others may

Below is the HTML content: <div class="wrapper"> <figure align="center"><img src="http://www.felipegrin.com/port/or-site.jpg" alt=""><br><span>RESPONSIVE HTML5 WEBSITE FOR <br> OR LEDS COMPANY</span></fig ...

What steps can be taken to deter users from bookmarking URLs?

On my website, the webpages are dynamically generated using the GET method to fetch variables from a specified URL. For instance, consider the code on the main page: index.php <p><a href="/dynamic.php?name1=value1&amp;name2=value2">next p ...

How do I go about aligning the first row to the center vertically?

When I use the align-items-center class in the row section, it just doesn't seem to work as expected: <div class="container"> <div class="row align-items-center"> <div class="col-12 bg-warning"> hello ...

Encountering a CouchDB 401 Unauthorized Error

I have a couchDB database named "guestbook". Initially, I utilized the following code to add a user to the "_users" database: $scope.submit = function(){ var url = "https://sub.iriscouch.com/_users/org.couchdb.user:" + $scope.name; console.log(url); $ht ...

Developing advanced generic functions in Typescript

I am currently working on a Hash Table implementation in Typescript with two separate functions, one to retrieve all keys and another to retrieve all values. Here is the code snippet I have so far: public values() { let values = new Array<T>() ...

cdkDropList does not function properly when used with ng-template in a dynamic component list

Exploring the new Drag&Drop features introduced in Angular Material 7, I am dynamically generating components using ng-template. <div cdkDropList (cdkDropListDropped)="dropLocal($event)"> <ng-template #components></ng-templat ...

Creating a unified border style for both <p> and <ul> tags in HTML5

Is there a way to have both paragraphs and unordered lists contained within the same border? I initially thought I could achieve this by placing the list inside the paragraph tag, but that does not seem to work. Below is a snippet of my external style sh ...

The most efficient method for retrieving data in React

Recently, I started working on a React App integrated with Riot API to display users' recent games and more. As part of this project, I'm utilizing React and NextJS (fairly new to NextJS). However, I'm contemplating the most efficient way to ...

Array contains a copy of an object

The outcome I am striving for is: dataset: [ dataset: [ { seriesname: "", data: [ { value: "123", }, { value: &q ...

When setting an empty URL with Fabricjs' setBackgroundImage function, a null reference error occurs in the _setWidthHeight

Recently, I stumbled upon an article detailing a method to clear the background of a fabric canvas... canvas.setBackgroundImage('', canvas.renderAll.bind(canvas)); In the development of my online design tool which utilizes Fabricjs 1.4.4, I have ...