Adding LocalStorage functionality to buttons in order to switch colors can be done by storing the

I've run into an issue trying to incorporate LocalStorage with the buttons that change colors as themes in JavaScript. I'm new to coding and eager to add this feature to my personal blog.

$(document).ready(function () {

$(".header--theme-button").on("click", function() {
  var primaryColor = localStorage.getItem("--theme-primary");
  var secondaryColor = localStorage.getItem("--theme-primary");

  var primaryColor = $(this).css("--theme-primary");
  var secondaryColor = $(this).css("--theme-secondary");


  $().change(function () {
    var primaryColor = $(this).val();
    $('.header--theme-button').css("--theme-primary");
    localStorage.setItem("--theme-primary", primaryColor);
    var secondaryColor = $(this).val();
    $('.header--theme-button').css("--theme-secondary");
    localStorage.setItem("--theme-primary", secondaryColor);
  });

  $(".header--theme-button").removeClass("active");
  $(this).addClass("active");

  $(document.body).css("--primary-color", primaryColor);
  $(document.body).css("--secondary-color", secondaryColor);
});

});

HTML: https://pastebin.com/KswauZRU

CSS: https://pastebin.com/85bH2J5w

Answer №1

Greetings from the world of stackoverflow! Are you facing errors in your code? It seems like a case where you may be accidentally overwriting primaryColor and secondaryColor.

Here's a revised version for you to try out:

$(document).ready(function() {
  var primaryColor = localStorage.getItem("--primary-color");
  console.log("localstorage primary: " + localStorage.getItem("--primary-color"));
  $(document.body).css("--primary-color", primaryColor);

  var secondaryColor = localStorage.getItem("secondary");
  console.log("localstorage secondary: " + localStorage.getItem("--secondary-color"));
  $(document.body).css("--secondary-color", secondaryColor);

  $( ".header--theme-button" ).each(function() {
    if($(this).css("--theme-primary")==primaryColor){
      console.log("found active element: "+primaryColor);
      $(".header--theme-button").removeClass("active");
      $(this).addClass("active");
    }
  });

  $(".header--theme-button").on("click", function() {

     $(".header--theme-button").removeClass("active");
     $(this).addClass("active");

     var primaryColor = $('.active').css("--theme-primary");
     console.log("primaryColor: " + primaryColor);
     localStorage.setItem("--primary-color", primaryColor);
     $(document.body).css("--primary-color", primaryColor);

     var secondaryColor = $('.active').css("--theme-secondary");
     console.log("secondaryColor: " + secondaryColor);
     localStorage.setItem("--secondary-color", secondaryColor);
     $(document.body).css("--secondary-color", secondaryColor);
   });
 });
 

I've created a handy fiddle (as the inline snippet didn't cooperate) for you to directly test this solution. Simply hit the "run" button on the top left corner to reload the code and witness the color retention.

Cheers, Paul

Answer №2

$(document).ready(function () {

$(".header--theme-button").on("click", function() {


  var baseColor = localStorage.getItem("theme-primary");
  var accentColor = localStorage.getItem("theme-secondary");
  console.log(localStorage.getItem("theme-primary"));
  console.log(localStorage.getItem("theme-secondary"));

  // var primaryColor = $(this).css("--theme-primary");
  // console.log(this);
  // var secondaryColor = $(this).css("--theme-secondary");





  $(".header--theme-button").removeClass("active");
  $(this).addClass("active");

  $(document.body).css("--base-color", baseColor);
  $(document.body).css("--accent-color", accentColor);

  var updatedBaseColor = $('.active').css("--theme-primary");
  localStorage.setItem("theme-primary", updatedBaseColor);
  console.log(updatedBaseColor);
  console.log(localStorage.setItem($('--theme-primary'), updatedBaseColor));
  var updatedAccentColor = $('.active').css("--theme-secondary");
  localStorage.setItem("theme-secondary", updatedAccentColor);
  console.log(updatedBaseColor);
  console.log(updatedAccentColor);

});




});

Hello there! Give this code a try. It now remembers your last color choices!

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

After clicking, I would like the text from the list item to have a style of "background-color: aqua" when displayed in the textarea

Is there a way to apply a highlight with a style of "background-color: aqua" in the textarea only to the word selected from the list above after clicking on it? See below for my HTML: <head> <script src="https://ajax.googleapis.com/ajax/libs/ ...

What could be the reason for the lack of rerendering in this child component?

Currently, I'm delving into ReactJS and attempting to grasp how child component rendering functions. To illustrate, consider the following example: var externalCounterVar = 10 class Counter extends React.Component { constructor(props){ super(pr ...

Create a Bootstrap grid that perfectly fits the viewport without any overflowing content

I'm currently utilizing Bootstrap 5 in an attempt to design a simplistic layout consisting of an MxN grid of cells, each of equal size. My goal is to have this grid fill the entire viewport without any scrollbars appearing in either direction. However ...

Unable to configure AngularJS inputs to have a blank default value

I am facing a peculiar issue where I am unable to initialize my input fields as blank/empty. Even after clearing the cache and performing a hard reload, Google Chrome seems to be auto-populating them with older cached values. Here is the current view: Th ...

Unexpected behavior encountered when implementing specific Textfield validation with Material UI

Currently running a project on Node and utilizing React for the front-end, I have encountered an issue with setting .env variables. The project is built with Material UI, and most TextFields are working as expected with their specified validation rules. ...

Injecting data into a Q promise

I'm facing some issues related to what seems like JavaScript closures. In my Express + Mongoose web application, I am utilizing the Q library for Promises. I have a question regarding passing request data to the promise chain in order to successfully ...

Utilizing JQuery Mobile to handle multiple forms on a single page and submitting each form uniquely by its ID using JQuery Post

After experimenting with assigning the same form ID to all forms on the page and also giving each form individual IDs with unique.submit functions, I encountered an issue where only the first form would work while the rest would redirect me back to the hom ...

Unable to perform the 'setSelectionRange' function on the 'HTMLInputElement' due to the input element's type being 'number', which does not allow selection

My attempt to enable text selection in an input box upon user click by using the code snippet below was unsuccessful: <input type="number" onclick="this.setSelectionRange(0, this.value.length)" name="quantity" /> Instead of achieving the desired ef ...

Obtain a compilation of users who have expressed their reaction to a message with a specific emoji on Discord

Check out this Discord.js code snippet for a Discord bot: client.channels.fetch('channelID here').then(function (channel) { channel.messages.fetch('messageID here').then(function (message) { console.log(message.reactions.cache.get(&a ...

Stop Gmail from Removing Attached HTML Files

I successfully developed an HTML file with its own CSS styling and custom HEAD tags to ensure it displays well in mobile browsers. I managed to make it work with PHP as a file attachment. However, the issue arises when Gmail distorts the view of the file ...

The typeof operator is not functioning as anticipated when used with an ajax response

Trying to implement form validation using AJAX and PHP, but encountering issues with the typeof operator. The validation works smoothly except when receiving an empty response, indicating that all fields have passed. In this scenario, the last input retai ...

The situation where a Javascript switch case continues to fall through to the default case even when a 'break' statement

I am currently setting up a node.js discord bot that utilizes firebase to save a user's status. My switch statement is functioning smoothly, handling each command effectively. The default case looks like this: default: message.reply("Unknown comm ...

Retrieve events triggered by each element

Currently, my research centers around digital marketing and user experience. In order to gather the necessary data for this study, I must collect event logs from all components within a UI to create datasets on usability patterns. In a web interface, such ...

Utilizing KnockoutJS to Apply CSS Binding Based on Dropdown Selection

Check out the live example here: http://jsfiddle.net/0gmbbv5w/ In my application, I have an object retrieved from the database that I bind to a <select> var NoticeType = function (noticeType) { this.NoticeTypeId = ko.observable(noticeType.Notic ...

ngInfiniteScroll Activates on Every Scroll Occurrence

Implementing ngInfiniteScroll for endless scrolling on my website has required me to set the height of the outer div to a specific value. Without this adjustment, the Infinite Scroll feature activates unintentionally. <div style="height: 1px"> &l ...

Font-face src with local() is incompatible with Android devices

(I apologize for not discovering this earlier, but it seems that Chrome-Android also does not support the font I intended to use. The fallback-to-sys-default-font-trick used by Chrome-Android did fool me.) I had planned to incorporate unicode-range to add ...

Loop through the array while handling a promise internally and ensure completion before proceeding

I am currently working on populating a response array with Firestore snapshots and creating download links for stored files within each snapshot. Despite trying various solutions involving Promises, the response array consistently ended up being null. do ...

jquery-powered scrollable content container

<script language="javascript"> $(document).ready(function($) { var methods = { init: function(options) { this.children(':first').stop(); this.marquee('play'); }, play: function( ...

Leveraging Next.js to efficiently handle multiple asynchronous requests with NextResponse

I have developed a login/signup application using NextJS. When attempting to log in, the logic in my route.ts file sends requests to a MongoDB database to check if the user exists and if the password is correct. However, instead of receiving the expected 4 ...

Tips for Excluding Content Retrieved Through file_get_contents?

Currently, I am storing the source code of a webpage in a variable called $html using the following line: $html = file_get_contents('http://www.google.com'); When I use <textarea><?php echo htmlentities($html); ?></textarea> ...