Utilize jQuery to set a cookie, then apply the bodyclass retrieved from the cookie upon page

I have a button that changes the body class to .blackout

For this, I am utilizing js-cookie library to manage cookies. The code snippet associated with my button is shown below:

<script>
$('#boToggle').on('click', function(e) {
  $('body').toggleClass('blackout'); 
});
</script>

My dilemma lies in incorporating Cookies.set('name', 'value'); from the aforementioned link to set the cookie while toggling classes using .toggleClass and also how to retrieve the cookie data to apply it back as the body class.

Any assistance on this matter would be greatly appreciated!

Answer №1

If you're looking to persist the state of your toggled class across sessions, using Cookies is one option but localStorage might be a more suitable choice.

Let me show you how to achieve this with both methods.

Using Cookies

To understand the difference between utilizing Cookies and Local Storage, take a look at this thread. Either method should work in your case, although Local Storage has an advantage as it doesn't require an extra library.

let toggleState = Cookies.get('toggle');
$(body).toggleClass('.blackout', toggleState)

Using Local Storage

let toggleState = localStorage.getItem('toggle');
$(body).toggleClass('.blackout', toggleState)

With the updated code snippet

var localStorageToggle = localStorage.getItem('toggle');
var toggleState = localStorageToggle ? localStorageToggle : false;

$('#boToggle').on('click', function(e) {
  $('body').toggleClass('blackout', toggleState);
  localStorage.setItem('toggle', toggleState);
});

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

Display notification following successful data saving in CodeIgniter

I attempted to set up a notification to appear when saving data and displaying it in the view, but it didn't work as expected using notify.js. Can someone offer some assistance? This is my save function: function save() { $data = array( ...

Learn how to implement a jQuery plugin within an AJAX request

Issue with PHP website: Trying to display an image on button click within the same webpage using an imageViewer effect. Currently, the image opens in a different webpage. Any help with code snippet would be greatly appreciated. Thank you! <script type= ...

Tips for successfully importing .eot and .woff documents using Babel?

When attempting to start my project, I encountered the following error message (You may need an appropriate loader to handle this file type.) for .eot, .woff, .ttf, and .svg files: ERROR in ./src/styles/fonts/nm/icons/nm-icons.svg?aaf8685e87a6901c76c52d00 ...

Node.js dynamically updates exports for efficient code execution

I am facing an issue with exporting and importing an object in my code. The object starts off empty but gets populated with keys and values when a button is clicked. However, when other files import this object, it still shows as empty. How can I dynamical ...

Unable to include Authenticated Routes in react router dom

Currently, I am utilizing react-router-dom to manage routing for users who are authenticated and non-authenticated. However, I have encountered an error in Element due to missing properties. Is there a way to make withoutAuth() function properly for authe ...

JavaScript - The AJAX response is consistently after being undefined

I am encountering an issue with the following functions: function get_non_authorized_bulk_edit_option_values() { var modificable_column_names = get_write_user_values(); alert(modificable_column_names); } The above function is calling this ...

Ensure that the width of the sibling div matches the width of its sibling image

I need help displaying an image with two buttons positioned below it. The dimensions of the image can vary, so I've set a max-width of 60% and max-height of 80%. However, I'm struggling to align the buttons correctly under the image - with the le ...

Releasing the mouse button after dragging successfully without the use of any libraries

I have implemented a pure CSS snap scroll feature and now I need to determine the position of an element in relation to the viewport once the user stops dragging. However, I prefer not to rely on any complex libraries as I do not require any actual movemen ...

How can jQuery be forced to accept an XHTML string as XML?

For my OpenID implementation in Javascript, I'm using AJAX to fetch a remote page source and searching for the <link rel="openid.server" href="http://www.example.com" /> tag within the head section. I have opted for the jQuery library for the AJ ...

Manipulating the DOM by nesting an icon within a button element in HTML

Currently working on my todo list project and I have a question about using innerHTML. I'm curious if I can include an icon inside of a button tag like this: btn.innerHTML = '<i class="fas fa-times fa-lg"></i>'; So, wo ...

The browser is failing to send cookies to the backend and is also not properly setting them initially

Greetings everyone, I am currently in the process of securing my spring boot application with HTTP only cookies, transitioning from local storage. However, I have encountered some challenges along the way that even chatGPT couldn't resolve :) Let&apo ...

The main.js file will be served by nodeJS using express

After developing a nodeJS server using express, I encountered an issue where the server was only delivering the index.html file and not the accompanying main.js file. Both files are located in the same directory. app.get('/', function (req, res) ...

Creating an interactive time selection tool with two dropdown lists that are dependent on each other using HTML and JavaScript

Hi everyone, I am new to JavaScript. I am currently working on creating two dropdown lists, one for 'Start Time' and another for 'End Time'. These dropdown lists will display hours in a 24-hour format with intervals of 30 minutes. In t ...

How is the server architecture typically designed in a node.js application?

Currently, I am developing a node.js application using socket.io and I'm seeking advice on how to structure the folders properly. The files that I have in my project include: Server.js package.json Additionally, I have: Client.js Index.html Incl ...

Next.js manages 0Auth authentication using MoneyButton for authorization

I have been working on implementing 0Auth user authorization for my Next.js application using the MoneyButton API. Successfully, I am able to initiate the authorization request with client.requestAuthorization('auth.user_identity:read','http ...

Determine whether the user has authorized the website with long-term access to obtain location information in the browser

Everything is running smoothly as I call navigator.geolocation.getCurrentPosition in my web app. Users are guided to a screen that explains the benefits of sharing their location, and once they press a button, the request is initiated without any issues. ...

What are the steps to integrate TypeScript into JavaScript code?

How can I import a TypeScript class in a Node CommonJS JavaScript file? When using mongoose in my TypeScript code, I typically do the following: // user.model.ts export const UserModel = model<User>('User', schema); In my JavaScript code: ...

NPM is currently malfunctioning and displaying the following error message: npm ERR! 404

When running npm update -g, the following error occurs: npm ERR! code E404 npm ERR! 404 Not found : default-html-example npm ERR! 404 npm ERR! 404 'default-html-example' is not in the npm registry. npm ERR! 404 You should bug the author to publi ...

The radial gradient in d3.js does not properly affect paths

My goal is to create a radial gradient on my path element, but for some reason the radial gradient does not apply correctly. Can anyone help me troubleshoot this issue? Below is my updated code: // Define the canvas / graph dimensions var margin = {top: ...

Is it possible to verify if the provided form input variable exists within an array? Can anyone point out any oversights?

Feeling a bit lost here, not sure what I've missed. Any help would be greatly appreciated as my calculations never seem to come out right. function validateZip(){ var zipCode = $("input[name='zipCode']").val(); var redRiverHondaZips = ...