Default setting for the sidebar to be collapsed

I'm a beginner in web development and still learning HTML, CSS, and JS. I tried following a YouTube tutorial to create a collapsible sidebar, but for some reason it's collapsed by default and I can't figure out how to make it open. It seems like I don't fully understand what's happening in my code. Can someone please help me identify the issue and explain how this should work?

HTML:

<div id="wrapper">
    <div id="sidebar-wrapper">
        <ul class="sidebar-nav">
            <li>
                <a href="#selectGameSubmenu" data-toggle="collapse" aria-expanded="true" class="dropdown-toggle">
                    <i class="fa fa-fw fa-gamepad"></i> Select something</a>
                <ul class="collapse list-unstyled">
                    <li>
                        <a href="#">Link1</a>
                    </li>
                    <li>
                        <a href="#">Link2</a>
                    </li>
                    <li>
                        <a href="#">Link3</a>
                    </li>
                </ul>
            </li>
            <li>
 
        ....(Code continues)

CSS:

#sidebar-wrapper{
    z-index: 1;
    position: fixed;
    
   ...(Code Continues)

JS:

$("#menu-toggle").click(function(e){
    e.preventDefault();
    $("#wrapper").toggleClass("menuDisplayed");
});

Answer №1

Alright, let me guide you on how to accomplish your desired outcome using two different methods. After that, I will provide an explanation of how your current code functions.

Method 1:

Firstly, within your initial div (#wrapper), include the class menuDisplayed:

<div id="wrapper" class="menuDisplayed">

Method 2:

You also have the option to adjust your CSS properties to achieve your goal and set "menu displayed" as the default style:

  1. Replace all instances of "menuDisplayed" with "menuHidden" throughout your code for better semantic understanding.
  2. Update the styles for #sidebar-wrapper by assigning a width value other than 0.
#sidebar-wrapper{
    z-index: 1;
    position: fixed;
    width: 250px;
    height: 100%;
    overflow-y: hidden;
    transition: 0.15s;
    background-color: var(--black) ;
    font-size: 1em;
}
  1. Similarly, modify the styles for #page-content-wrapper to accommodate space for the sidebar:
#page-content-wrapper{
    width: 100%;
    position: absolute;
    padding: 15px;
    padding-left: 250px; /* allowing 250px of space on the left */
    transition: 0.15s;
    color: black;
}
  1. The final step involves adjusting the styles for the closed sidebar:
#wrapper.menuHidden #sidebar-wrapper{
    width: 0; /* 'wrapper' element with 'menuHidden' class should have width set to 0 */
}

#wrapper.menuHidden #page-content-wrapper {
    padding-left: unset; /* removes the attribute providing space for the sidebar */
}

Now, let's dive into how your existing code operates (prior to altering the sidebar functionality):

Your CSS instructs the browser that the element with the sidebar-wrapper id should initially have zero width (hidden upon page load). However, it specifies that when this element is nested inside another element with both the wrapper id and the menuDisplayed class, its width should be 250px.

The magic happens in your JavaScript code: It triggers the toggling of the menuDisplay class within the element with the wrapper id. This action activates the corresponding CSS style making your sidebar visible at 250px wide. Reversing this toggle removes the menuDisplayed class from the wrapper element, returning the sidebar width to 0.

The $("#menu-toggle").click function sets up an event listener for the 'click' event using jQuery. Upon triggering this event (clicking on the element with the menu-toggle id), the associated callback function is executed:

function(e){
    e.preventDefault(); // prevents default element behavior (e.g., anchor (<a></a>) links not functioning)
    $("#wrapper").toggleClass("menuDisplayed"); // toggles the 'menuDisplayed' class of the element with the 'wrapper' id
}

Answer №2

To ensure that the navbar is displayed when the page loads, simply include the class menuDisplayed in the initial setup of the navigation bar (identified by the id #wrapper).

<div id="wrapper" class="menuDisplayed">

Answer №3

Make sure to include the CSS class menuDisplayed in your HTML element with the ID of #wrapper. This will ensure that it is displayed by default.

<div id="wrapper" class="menuDisplayed">

For a complete example, visit this link: http://jsfiddle.net/9ojvnutc/

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

Inline Styling with CSS Media Types

Creating a single HTML file is my current project requirement. I am looking to incorporate CSS in order to ensure that links within the document are clearly visible and easy to find (perhaps styled as blue with underlines) when accessed through a web brows ...

Combine a frame with a photo side by side

When I put a frame and a picture together, my photo is not fully displayed. In each size (such as mobile phone, larger size, and medium size), only a part of the image is shown. Can anyone help me with this issue? Here is my HTML markup: <!-- about sec ...

Creating a Custom FlatList Content Container with React Native

Is it possible to customize FlatList items with a custom component? I want to create a setup where my FlatList items are encapsulated within a custom component similar to the following: <ScrollView pt={8} px={16} pb={128} > <Card e ...

Guide on incorporating Bootstrap 4 beta.2 into an Angular 4 project

After attempting to install Bootstrap 4 version beta.2 along with its dependencies (jquery and popper.js), I encountered a strange problem. A SyntaxError message kept appearing in the console, specifically stating "SyntaxError: export declarations may only ...

A guide on implementing CSS and Styling in a React component

Struggling to style my React.js file that was converted from a standard web page. I have the original CSS but unsure how to use React for proper styling. Any assistance is welcomed! var NavBar = React.createClass({ render: function() { return ( ...

Freezing in IE/Safari due to AJAX jQuery interactions

Feeling frustrated and seeking help. I am currently executing this particular script: <script type="text/javascript" charset="utf-8> jQuery(window).ready(function(){ //alert('running'); var sold = false; var l ...

Using Javascript to extract and organize JSON arrays from various sets of checkboxes

Is there a way to automatically create an array of multiple groups of arrays like this: arr = {arr1:{index:value, index2:value2}, arr2:{index,value, index2:value2}}; The order is based on groups of checkboxes in HTML (see example below): <div class=& ...

The vertices in Three.js BufferGeometry refuse to update

As I strive to connect grid tiles with real elevation data from IndexedDB, I encounter a challenge due to the imperfect data resolution on the STRM elevation causing discrepancies at the edges between the tiles. To address this issue, my goal is to average ...

Position the image in a responsive manner relative to the text

I've successfully centered my h1 in a div using the following CSS properties: text-align: center; line-height: 150px; vertical-align: top; Now, I'm facing a challenge where I want to position an image in the top-left corner of the text. I want ...

Preventing the elements within a div section from shifting position

I am facing an issue with a div section that contains multiple <a href=""> tags. When I shrink the div section on the page, the contents move when a user tabs into it. Is there a way to lock the div section so that its contents do not move? For exam ...

Using Composition API to call a method on a child component

In my current project, I am facing a challenge with a parent component needing to call a method from one of its child components: <template> <div> <button @click="callChildMethod"> <child-component ref="child&q ...

How do I hide a dropdown menu when the selector's value changes in iOS6?

I'm currently developing a hybrid application using Worklight. When I tap on a select control, a native dropdown appears. However, when I choose an option and the onchange event is triggered, the dropdown doesn't disappear unless I tap on the do ...

What can I do to control the behavior of this shake effect?

Looking for a solution to the following coding issue: jQuery.fn.shake = function(intShakes, intDistance, intDuration) { this.each(function() { $(this).css("position","relative"); for (var x=1; x<=intShakes; x++) { $(this).a ...

Choose all the checkboxes alongside the markers on Google Maps

On this page , I have included a checkbox labeled "Select All" at the bottom, which automatically checks all other checkboxes. Although the code below achieves what I want, the marker icons are not showing up. How can this be fixed? $(document).ready(func ...

Schema validation with React Yup is an essential step in

Currently, I am utilizing Yup for email field validation: const Schema = Yup.object().shape({ email: Yup.string() .email("invalid email format") .required("Email is required"), ... Upon form submission, I verify if the email doma ...

form controls disappear upon adding form tags

Currently experiencing an issue with angular and forms that I could use some help with. I have a dynamic form that is functioning properly, but now I need to add validations to it. After following this guide, I established the structure correctly. Howeve ...

Developing a MySQL Community Server-backed RESTful Web Service with the power of jQuery AJAX

I am currently in the process of developing a RESTful Web Service using MySQL Community Server alongside jQuery AJAX Unfortunately, my usage of jQuery AJAX is not functioning as expected. When attempting to add, delete, update a product, or retrieve all p ...

What can I do to remove the hidden <p> tags that Wordpress is inserting into my HTML code?

There seems to be some extra space appearing between my divs (inside a main div) that is possibly due to unexpected <p> and </p> tags being added by WordPress. This issue is quite common with WP, but the problematic tags are hidden so I am unab ...

When clicking on links that are not within the ng-view element, you will be redirected to the

I'm having trouble coming up with a name for this question, but here's my current situation This is the structure of my template: ├── index.html ├── ... ├── account │ ├── index.html │ ├── authorizat ...

Conflicting jQuery links arise when utilizing version 2.1.4 of jQuery

I have encountered a conflict with the jQuery link while using the LIMITLESS theme. Can someone please assist me in resolving this issue? <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script> The conflict is ...