Don't forget about managing cookies in JavaScript!

Currently, I am developing a left sidebar menu that expands and collapses upon clicking a button.

I need to find a way to save the state of the menu, whether it is expanded or collapsed, so that when the page is refreshed, the same class will still be applied.

$('#menu-action').click(function() {
  $('.sidebar').toggleClass('active');
  $('.main').toggleClass('active');
  $(this).toggleClass('active');

  if ($('.sidebar').hasClass('active')) {
    $(this).find('i').addClass('fa-close');
    $(this).find('i').removeClass('fa-bars');
  } else {
    $(this).find('i').addClass('fa-bars');
    $(this).find('i').removeClass('fa-close');
  }
});

// Provide hover effect for the menu
$('#menu-action').hover(function() {
  $('.sidebar').toggleClass('hovered');
});

Answer №1

Consider utilizing Window.localStorage:

$(document).ready(function() {
    if(localStorage.getItem("active")) {
        $('.sidebar').addClass("active")
    }
});

$(window).on('beforeunload', function() {
    localStorage.setItem("active", $('.sidebar').hasClass("active"));
});

Note that not all browsers support local storage. Check the provided link for more information. For older browser compatibility, you can opt for solutions like store.js.

Alternatively, you can explore using a cookie plugin as recommended here.

Answer №2

If you are unsure about the best way to handle reading or writing cookies, consider using the js-cookie library for a more streamlined approach. While it is possible to manage cookies with plain JavaScript, it can be quite cumbersome.

An example of how you could implement this library is shown below (Assuming you have included js.cookie.js in your HTML file):

// Save references to frequently used elements
var $menuAction = $('#menu-action');
var $menuActionI = $menuAction.find('i'); // the <i> inside #menu-action
var $sidebar = $('.sidebar');
var activeClass = 'active';

// Reference: https://github.com/js-cookie/js-cookie/tree/v2.1.0#basic-usage
var isActive = Cookies.get('site-menu-active') || false;

function toggleMenu() {
    $sidebar.toggleClass('active', isActive);
    $('.main').toggleClass('active', isActive);
    $menuAction.toggleClass('active', isActive);
    $menuActionI.toggleClass('fa-close', isActive);
    $menuActionI.toggleClass('fa-bars', isActive);

    isActive = !isActive;
    Cookies.set('site-menu-active', isActive, { expires: 7 });
 }

// Call immediately to set initial state based on cookie value
toggleMenu();

// Add click functionality
$menuAction.click(toggleMenu);

// Add hover effect to menu
$menuAction.hover(function() {
    $sidebar.toggleClass('hovered');
});

Answer №3

When it comes to managing data in web applications, Html5 storage proves to be a valuable tool. It offers the flexibility of switching between localStorage and sessionStorage based on specific needs:
1)localStorage - data persists even after closing the browser
2)sessionStorage - data is cleared upon closing the browser
Stored data can also be easily removed as needed

$('#menu-action').click(function() {
  $('.sidebar').toggleClass('active');
  $('.main').toggleClass('active');
  $(this).toggleClass('active');

  localStorage.setItem("active", $('.sidebar').hasClass('active'));

  if ($('.sidebar').hasClass('active')) {
    $(this).find('i').addClass('fa-close');
    $(this).find('i').removeClass('fa-bars');
  } else {
    $(this).find('i').addClass('fa-bars');
    $(this).find('i').removeClass('fa-close');
  }
});

$(document).ready(function(){
  if(localStorage.getItem("active")){
      $('.sidebar').addClass('active');
      $('.main').addClass('active');
      $('#menu-action').find('i').addClass('fa-close');
      $('#menu-action').find('i').removeClass('fa-bars');
  }
});

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

Using JQuery's appendTo method with a lengthy string of elements that includes a mix of single and double quotes: a step-by-step guide

My content script is fetching data from the server in the form of an array of objects. The structure looks something like this: [ { "lang": "English", "videos": [ { "embed": "<iframe width='100%' height='421px&apo ...

How to maintain the selected value in a Vue.js dropdown even after the page is refreshed

When a user selects a value from a dropdown, it is pushed to the URL. If the page is refreshed, the dropdown should default to the selected value in the URL. This functionality is being implemented in Laravel. I have attempted the following approach, but w ...

Offspring maintain a certain position within the larger framework of their parent on a

When resizing the parent wrap container, how can I ensure that the pin (red dot) on the image maintains its relative position? To see the issue, resize the wrap container. #wrap{ position: absolute; width: 100%; height: 100%; top: 0; l ...

Encase the event handler within JQuery

Here's an example of inputs with OnBlur event handlers: <input name="abc" tabIndex="5" class="datetime" onblur="if (CheckMode(this))__doPostBack('abc',''); else return false;" /> Now, in JQuery Form ready function, I want ...

A helpful guide on incorporating and showcasing a 'svg' file within a React Native application

I am having an issue with importing an svg file in my code. The svg file has a complex structure with various paths: <svg xmlns="http://www.w3.org/2000/svg" width="260.346" height="65.709" viewBox="0 0 260.346 65.709&q ...

Turn off Grammarly on a WordPress Site

It has come to my attention that Grammarly is causing issues with the functionality of the forms on our website. I have come across information stating that adding the following attribute to all input fields can resolve this problem and block Grammarly fr ...

Troubleshooting: jQuery AJAX failing to receive JSON data in HTTP request

Experimenting with HTML and jQuery to practice JSON requests, I conducted some research and attempted a small test. However, upon running the script in Google Chrome, only my HTML/CSS elements appeared instead of expected results. Below is the code snippet ...

Populate the named dynamic array with information

I need to implement a dynamic array data adding functionality in JavaScript/Vue.js. Adding data to an array is straightforward: methods: { add: function add(e) { e.preventDefault(); if (!this.newName) return; this.config.name ...

Following the submission of a POST request, an error occurred stating: "Unable to assign headers once they have been sent to

I'm having trouble figuring out what's wrong with my code. Whenever I send a post request, I get an error message saying "Cannot set headers after they are sent to the client". My model includes a comment schema with fields for user, content, and ...

Is there a way to show the input value in a different form while still retaining the original value?

When receiving a pagination number from user input, I store it in a variable like so: $html .= "<input type='submit' name='next' value='$next_page_number' />"; Now, I'm looking to replace the displayed text for th ...

The functioning of JavaScript's ajax capabilities

Need some help with a coding issue I'm facing. Can anyone provide suggestions for improving my code? I've come across a situation where the table is not updating when using a certain piece of code. However, upon further inspection, I found that ...

Guide to sending a response to an AJAX post request in Express with Node.js: Answered

For a project focused on practicing Node.js and jQuery Ajax, I'm working on a simple task. Essentially, I have an ajax post request that sends data to a Node.js server and waits for a response. On the server-side, there's code that processes this ...

The positioning of drawings on canvas is not centered

I'm facing an issue while attempting to center a bar within a canvas. Despite expecting it to be perfectly centered horizontally, it seems to be slightly off to the left. What could possibly be causing this discrepancy? CSS: #my-canvas { border: ...

Keeping the Drawer open in Material-UI: What you need to know!

I am looking to create a collapsible sidebar feature in Material-UI where only the icons are displayed when collapsed. I have successfully implemented the Mini Variant Drawer for the basic sidebar functionality, but I'm facing an issue with maintainin ...

Issue with Pebble SDK/SimplyJS failing to recognize the tab character

Currently, I am facing an interesting challenge while attempting to make my Pebble watch recognize the escape sequence character \t when sending data to my watch using SimplyJS. Here is the code snippet I have been working with: simply.scrollable(tr ...

What are the possible reasons for my load function failing intermittently?

I have encountered an issue with my app where sometimes the content is not loaded into a dialog. Most of the time it works perfectly, but occasionally it fails to display the content. Here is the code snippet that I am using: $('#popup_background&apo ...

Arranging by and loading progressively in AngularJS

Encountering an issue with the orderBy function in an ng-repeat paired with an auto-incrementing limitTo. After loading a few elements on the page, the directive ceases to function properly and stops increasing the element limit. Here is the HTML code sni ...

Having issues with C# ASP.Net autocomplete not functioning properly when using Javascript/Json post

I have been working on a c# asp.net usercontrol that requires a functional autocomplete feature. However, I am encountering an ongoing issue where the script appears to be running – with the progress bar spinning – but it consistently returns an ' ...

When the input CTRL+C is entered in the console, Node.js / JavaScript will output

I have a script that I use to restart another script. Here is the code snippet: catch(err){ console.log(err) webhook.send(`Error monitoring **www.-.com**, restarting monitor.`) await browser.close() await sleep(monitorDelay) return chec ...

"Enhance your website with the ability to dynamically load and display

I am facing a little issue and need suggestions because I am struggling with inserting data into an HTML page using the append jQuery function and AJAX request. Within my HTML block, under ul elements, there are some images that I directly insert into the ...