Encountering numerous challenges while attempting to create a switch theme button with the help of JavaScript's localStorage and CSS variables

It's frustrating that despite all my efforts, I'm still stuck on implementing a small feature for the past 5-6 hours. I need assistance with storing a single variable in the user's localStorage, initially set to 1. When the user clicks a button, the localStorage value switches between 0 and 1, toggling between light and dark mode on the website. The code for the button can be found in the second try or my previous StackOverflow post.

Here are some of my attempts at implementation:

Code working without local storage, initial value 0:

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

<head>
    <meta charset="UTF-8>
    ... (remaining code)
</body>

</html>

... (more content) The original idea was: A CSS variable is set to 1 initially and should change to 0 on button click. Even after refreshing the page, it should remain at 0. Thanks.

EDIT:

Integration of solution into project:

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

<head>
    <meta charset="UTF-8>
    ... (updated content)
</body>

</html>

Answer №1

It seems like brushing up on your JavaScript skills might be beneficial, especially considering the syntax errors present.

Consider checking out these resources for further learning:

  1. JavaScript Reference
  2. Learn JS at freecodecamp.org
  3. Learn JS at Codecademy
<!DOCTYPE html>
<html lang="en">

  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
      :root {
        --numvar: 0;
      }

      html {
        filter: invert(var(--numvar));
      }

    </style>
  </head>

  <body>
    <button id="res" onclick="change()">hi</button>
    <script>
      if (!localStorage.getItem('thisvarisgood')) {
         localStorage.setItem("thisvarisgood", "1")
      }

      function change() {
        if (localStorage.getItem('thisvarisgood') == '1') {
          localStorage.setItem("thisvarisgood", '0')
        } else {
          localStorage.setItem("thisvarisgood", '1')
        }

        var num = Number(localStorage.getItem('thisvarisgood'));
        let root = document.documentElement;
        root.style.setProperty("--numvar", num);
      }
      var num = Number(localStorage.getItem('thisvarisgood'));
      let root = document.documentElement;
      root.style.setProperty("--numvar", num);

    </script>
  </body>

</html>

Answer №2

The main issue with the recent attempt is that the variable was defined as "thisvarisgood" but accessed as "thisvarisgud."

To fix this, you should adjust how the CSS is modified. The script itself cannot handle this task since it only runs once. Instead, make sure to set the style within the function that updates the local storage value and also on page load.

Additionally, the other response has already provided a solution for you by correcting the localStorage variable name and setting the style within the function (lines 35-37). The styling for "on page load" can be found in lines 40-41.

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

javascript selecting window location strings

Hey there, http://localhost/estamo/asset.php?aname=VklQIFBsYXph&di=Ng== I have this URL and I want to retrieve it using Javascript: var locat = window.location.href; $.get("enviaramigo.php?email="+$("#email").val()+"&url="+locat, function(h ...

Retrieving registered components dynamically in Vue.js

Check out my scenario on jsBin In my setup, I have a selector <component :is="selectedComponent"></component>, along with a <select v-model="currentComponent">...</select> that allows me to choose which one is displayed. Currently ...

Implementing automatic token refreshing and automatic logout features in Vue

I am a novice web developer looking to enhance my skills. For my initial project, I decided to incorporate Laravel and Vue. My main objectives are to: Implement an auto-logout feature after 3 minutes of user inactivity Create an automatic ping to my token ...

Which phase is affected by the stopPropagation method?

Quirksmode explains that modern browsers have a capturing phase as well as a bubbling phase, which you can read more about here. If I decide to implement stopPropagation in my event handler with a Boolean argument specifying the phase, how will it behave? ...

Developing with node and express: optimizing your workflow

After researching various blogs and tutorials on node + express development workflow, there is one crucial aspect that seems to be missing: When developing, which version of the app should you have open in your browser? The source app, featuring clean, ...

"Enhancing the user experience: Triggering a window resize event in jQuery before page load on Magento

I am trying to trigger this function before the page finishes loading, but currently it only triggers after the page has loaded. Can anyone assist with this issue? $(window).on('load resize', function(){ var win = $(this); //this = window ...

(angular 8) Error occurred when converting a file or image to FormData due to an invalid value (Note: FormData object printed as Object Form{})

I encountered an issue where I am getting an invalid value from form data. The value appears correct in `this.fileData` with a size of 5701, but becomes empty when converted to form data - `{}` is logged when I console.log the form data. Additionally, acce ...

What is the best way to convert my query for use with MongoDB in a Node.js application?

Here is the structure of my MongoDB query: db.test.findOne({"User.David":{$elemMatch:{"action":"todo","status":"Done"}}}) I am currently developing a node.js API that allows users to retrieve documents based on username and status. Below is my attempt a ...

Create a new tab that is active and use ng-repeat in the uib-tab directive

I've been trying to solve this problem for a while now. I came across a similar post, but it was left unanswered. So, I decided to create my own post with a Plunkr example. The issue I'm facing is that upon loading, the ui-tab always defaults to ...

Animating the dimensions of objects in THREEjs

In my project using THREE.js, I am aiming to create a captivating animation where an object gradually shrinks into nothingness. After exploring solutions on Three.js - Animate object size, I found methods to adjust the size of an object. However, the chan ...

Sorting technique failing to reorganize list

I'm currently troubleshooting why my sorting function is not functioning as expected. My goal is for it to operate similarly to this example: https://codepen.io/levit/pen/abmXgBR The data I am working with is retrieved from an API: <BookCard v-fo ...

Utilizing the variable $this outside of an object context within an Ajax function

Encountering the following error: Fatal error: Uncaught Error: Using $this when not in object context in E:\xampp\htdocs\StudentGuideBook\Version1.0\models\AjaxChecking.php:4 Stack trace: #0 {main} thrown in E:\xampp&b ...

Loading images in advance using jCarousel

I need help with preloading images on a jCarousel that loads a JSON feed and generates necessary HTML. Can anyone suggest a way to accomplish this task efficiently? $(".banner ul").jcarousel({ itemLoadCallback:loadTopBanner, auto: 6, wrap: ...

I am working with Vue.js 2.0 and attempting to send an event from a `child component`

I've been working with Vue.js 2.0 and I'm facing an issue trying to emit an event from a child component to the parent component, but unfortunately, it's not functioning as expected. Here is a glimpse of my code: child component: <temp ...

What is the best way to align geometry at the bottom of the screen in Three.js while still preserving its aspect

I recently started using Threejs and encountered an issue with positioning geometry. I'm trying to place the geometry at the bottom with half of it cut off, so only half should be visible. However, when I use position.setY(-300), the geometry moves do ...

What impact does setting everything to position:relative have on a webpage?

I stumbled upon some CSS / HTML examples and came across this interesting snippet: *, *:before, *:after { position: relative; } It appears that implementing this rule can have a notable impact on the layout. What might be the rationale behind this ...

The Javascript code is not running due to the XSS security measures in place

Within my Wordpress website, I have crafted an HTML form that enables users to view database records corresponding to their input. Following this AJAX tutorial on w3schools, a JavaScript function was implemented to send a GET request to a PHP script on the ...

transforming JSON into CSV structure

I am attempting to utilize a JSON file as input data. Below is an excerpt of sample data. [ { id: 1671349531, name: "A Wild Restaurant Expansion", blurb: "We are looking to expand from our current location to a new and better facility...", goal: 17000, pl ...

Is there a way to seamlessly integrate a PDF file into a KnockoutJS template without triggering any warnings from PDF plugins?

I am attempting to embed a PDF document in an HTML view, with the assistance of a Knockout ViewModel that supplies the URL for the document. I understand that the appropriate HTML element for this task is <object>, so my view looks like this: <di ...

Issue in Jquery: Unable to load the corresponding pages when toggling the checkbox on and off

I am facing an issue with a checkbox and calling different php pages based on the status of the checkbox. Currently, the code works only for checked checkboxes. I'm not sure why it's not working for unchecked checkboxes as well. <script type ...