What is the best way to toggle the visibility of a sidebar using a combination of jQuery and CSS

How can I make the sidebar appear when a button is clicked? It doesn't seem to be working.

I have implemented a jQuery code that toggles between classes when the button is clicked, and in the CSS file, it should hide/show the sidebar.

HTML:

<div id="sidebar">
    <img src="img/MyPicture.png" alt="MyPicture" class="headshot"/>
    <span style="font-weight:bold">MyName</span>
    <ul class="menu">
        <li class="active"><a href="#">Home</a></li>
        <li><a href="#">About</a></li>
        <li><a href="#">Projects</a></li>
        <li><a href="#">Contact</a></li>
    </ul>
</div>
<div id="wrapper">
    <div id="main">
        <div>
            <button id="sidebarToggle">Toggle Menu</button>
        </div>
        <h1>My Page</h1>
    </div>
    <div id="footer">
        <p>This is the footer</p>
        &copy; 2019 My Profile
    </div>
</div>

site.js:

var $sidebarAndWrapper = $("#sidebar,#wrapper");

$("#sidebarToggle").click(function () {
    $sidebarAndWrapper.toggleClass("hide-sidebar");
});

site.css:

#sidebar {
background:#17153e;
color:#c8c5d3;
position:fixed;
height:100%;
width:250px;
overflow:hidden;
left:0;
margin:0;
}

#sidebar.hide-sidebar {
    left: -250px;
}

#wrapper {
margin:0 0 0 250px;
}
    #wrapper.hide-sidebar {
    margin-left: 0;
}

Answer №1

Your solution is effective for me, ensure that your Jquery link is properly loaded. It appears to not be loading correctly. I utilized a cdn download and it is functioning perfectly, just give it a check.

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>

  <style>

#sidebar {
background:#17153e;
color:#c8c5d3;
position:fixed;
height:100%;
width:250px;
overflow:hidden;
left:0;
margin:0;
}

#sidebar.hide-sidebar {
    left: -250px;
}

#wrapper {
margin:0 0 0 250px;
}
    #wrapper.hide-sidebar {
    margin-left: 0;
}
  </style>
</head>

<body>
    <div id="sidebar">
        <img src="img/MyPicture.png" alt="MyPicture" class="headshot"/>
        <span style="font-weight:bold">MyName</span>
        <ul class="menu">
            <li class="active"><a href="#">Home</a></li>
            <li><a href="#">About</a></li>
            <li><a href="#">Projects</a></li>
            <li><a href="#">Contact</a></li>
        </ul>
    </div>
    <div id="wrapper">
        <div id="main">
            <div>
                <button id="sidebarToggle">Toggle Menu</button>
            </div>
            <h1>My Page</h1>
        </div>
        <div id="footer">
            <p>This is the footer</p>
            &copy; 2019 My Profile
        </div>
    </div>
    <script
  src="https://code.jquery.com/jquery-3.3.1.min.js"
  integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
  crossorigin="anonymous"></script>
  <script>
 var $sidebarAndWrapper = $("#sidebar,#wrapper");

$("#sidebarToggle").click(function () {
    $sidebarAndWrapper.toggleClass("hide-sidebar");
});
  </script>


</body>

</html>

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

Achieving Perfect Alignment for Absolutely Positioned Divs in

I'm currently facing an issue where the image I'm trying to center horizontally also moves the parent div downward when I try to vertically center it using top-margin. This is not the desired outcome. If you'd like to see what I mean, I&apo ...

Issue with displaying submenu in dropdown menu

I need assistance with a project I am currently working on. You can view the project here Everything seems to be functioning properly, except for when I click on the button Click to expand, the sub-menu (Link 1, Link 2, ...) appears far left of the button ...

Tips for examining/dumping Ionic variables

Seeking to investigate the $ionicTabsDelegate variable in my hybrid app, I employing a "dump" method, detailed in this helpful resource that can be found here. function dump(obj) { var out = ''; for (var i in obj) { out += i + ": ...

"Using a combination of Php, Html5, and xampp for

While attempting to run this PHP file using XAMPP, I encountered an issue. I am working on updating data in a database through a form submission. However, when I input the information and click submit, the page either just reloads or displays a message s ...

SVG: organizing objects based on event priority

I am struggling with layering and event handling in an SVG element. Check out the example here: https://stackblitz.com/edit/angular-ivy-rkxuic?file=src/app/app.component.ts app.component.ts import { Component, VERSION } from '@angular/core'; @ ...

Retrieve the variance between two arrays and store the additions in AddedList and the removals in RemovedList using typescript

I am still getting the hang of Typescript and I am trying to figure out the best solution for my issue. I have two arrays, A and B, and I need to identify the difference between them in relation to array A. The goal is to separate the elements that were ad ...

Issue with jQuery form submission not retrieving input value

[Beginner inquiry] I am using contact form 7 on my WordPress website. I have two input fields where I need to display the event title and price: if (window.location.href.indexOf("event") > -1) { var title = $('.entry-title').text(); var ...

Schema with nested object types in MongoDB

I currently have two schema files in my project. In the events.js file, I have an eventSchema defined. Here is a snippet of the code: var eventSchema = mongoose.Schema({ name:{ type: String, //required: true venue:{ } }); In another file named ve ...

Is jQuery's $.ajax causing a memory leak?

What is causing the memory leak in browsers like Firefox when using jQuery ajax? Check out this jsfiddle: http://jsfiddle.net/Rqfz7/ Many users have reported that running this code in Firefox causes a significant increase in memory usage. Have you experi ...

After the 1.24.1 update, VS Code no longer supports the HTML language mode

Recently, I encountered an issue after updating to the latest version of VS Code (1.24.1). The problem is that VS Code no longer recognizes HTML and fails to highlight or color the syntax properly. Emmet doesn't work, linter is unresponsive... it&apos ...

The function document.getElementById().value is malfunctioning

I've been working on a project focused on employee data stored in a MySQL database. To display this data in an HTML table, I utilized PHP. $sql = "SELECT * FROM Stock_Management.`staff_details`"; $result = mysqli_query($conn, $sql); if(mysq ...

Ways to manage numerous AJAX actions within a single HTTP request?

Currently, I am utilizing jQuery to create a multipart web page containing a list of links that are updated through periodic AJAX HTTP requests. Each link on the page is triggered by a timer in JavaScript, causing it to make an HTTP request to its designat ...

What impact will splitting a single file into multiple files have on the overall performance of the website?

Imagine having an index.php file that includes multiple other files: Contents of index.php --------------------------- include('header.php'); include('footer.php'); --------------------------- Contents of header.php ------------------ ...

What is the best method to determine the currency associated with the code in dinero.js?

Is there an easy way to locate the dinero currency in the dinero.js/currencies package using its code? For example, a function called getCurrency that accepts a string as input and outputs the corresponding dinero currency. ...

Transmit the date to the WCF RESTful service

I am using JQuery AJAX to call a WCF REST service from my JavaScript code. The service is set up with a bare style for the body, and I am unable to change it to wrapped. I need help sending a date parameter to the service. Can someone please assist me wi ...

Steps to customize the default thumbnail image of an embedded video that is not from YouTube

I've added a video to an HTML page. Here is the code: <div> <video width="400" controls> <source src="videos/myvideo.mp4" type="video/mp4"> </video> </div> Is there a way to modify the default thumbnail image of ...

Transfer the picture file and forward it to the rest API

import { Component } from '@angular/core'; import { Http, RequestOptions, Headers, Response } from '@angular/http'; import { Observable } from 'rxjs/Rx'; @Component({ selector: 'my-app', templateUrl: & ...

Regain focus after selecting a date with Bootstrap datepicker

When initializing a bootstrap datepicker from eternicode with the parameter autoclose: true, there are two undesired behaviors that occur: After closing the picker, tabbing into the next field causes you to start at the beginning of the document again, w ...

How can Vue allow for text selection to be encapsulated within a span element with two-way binding for styling

I have developed an application that allows users to highlight text with different colors while reading. For this functionality, I am utilizing the Selection API. However, I am encountering issues with the two-way binding aspect. When a user changes the c ...

Why isn't P5.JS's .display() working like it should?

I'm having trouble figuring out the scope of this code. I moved the function around, but I keep getting a "not a function" error. let bubbles = []; function setup() { createCanvas(400, 400); for (let i = 0; i < 10; i++){ bubbles[i] = new Bubbl ...