html - Storing and retrieving a theme in Javascript from a data-* attribute - Stack Overflow

I'm sorry if that's a duplicate, but I found myself in trouble as I can't get my theme m

I'm sorry if that's a duplicate, but I found myself in trouble as I can't get my theme mode stored in local storage.

Here is my HTML code:

<!-- 
  The data-* attribute is used to store custom data private to the page or application.
The data-* attribute gives us the ability to embed custom data attributes on all HTML elements.
-->

<body id="webPage" class="container" data-theme="light">
    <div class="">
        <h1>Hello world</h1>
    </div>
    <div class="">
        <button id="toggleDarkMode" type="button" class="" onclick="darkMode()">
          Click Me !
        </button>
    </div>
    <div class="">
        <a href="#">
      This is a link
    </a>
    </div>
</body>

As you can see, everything is handled by data-theme="light" to apply my css and onclick="darkMode()" to trigger my javascript. Here is the CSS:

:root {
    --colour-bck: #FFFAFA;
    --colour-font: #222;
}

[data-theme="light"],
a {
    transition-duration: 1s;
}


/* If mode is swicthed, then apply following changes to the variable  */

[data-theme="dark"] {
    --colour-bck: #222;
    --colour-font: #FFFAFA;
    transition-duration: 1s;
}


/* Styling the DOM */

body {
    margin: 0
}

.container {
    height: 100vh;
    background-color: var(--colour-bck);
}

body {
    color: var(--colour-font);
}

a {
    text-decoration: none;
    color: var(--colour-font);
    display: block;
    margin-top: 2em;
}

And the JavaScript:

/*
    darkMode switches to a dark/light mode view : body which renders the mode is fetch alongside data-theme holding the styles to render
    if the theme is dark, change it to light, which applies "data-theme = light" styles & vice-sersa
*/
console.log(localStorage)


function darkMode() {
    const container = document.getElementById('webPage');
    // const theme = container.getAttribute('data-theme');

    var dataTheme = container.getAttribute('data-theme');
    localStorage.setItem("theme", dataTheme);

    (localStorage.theme === 'dark') ? container.setAttribute('data-theme', 'light'): container.setAttribute('data-theme', 'dark');

}

Now, the thing is, I don't get any errors, and my value is saved into localStorage according to the console.log(). Hence my question, what did I do wrong?

I'm sorry if that's a duplicate, but I found myself in trouble as I can't get my theme mode stored in local storage.

Here is my HTML code:

<!-- 
  The data-* attribute is used to store custom data private to the page or application.
The data-* attribute gives us the ability to embed custom data attributes on all HTML elements.
-->

<body id="webPage" class="container" data-theme="light">
    <div class="">
        <h1>Hello world</h1>
    </div>
    <div class="">
        <button id="toggleDarkMode" type="button" class="" onclick="darkMode()">
          Click Me !
        </button>
    </div>
    <div class="">
        <a href="#">
      This is a link
    </a>
    </div>
</body>

As you can see, everything is handled by data-theme="light" to apply my css and onclick="darkMode()" to trigger my javascript. Here is the CSS:

:root {
    --colour-bck: #FFFAFA;
    --colour-font: #222;
}

[data-theme="light"],
a {
    transition-duration: 1s;
}


/* If mode is swicthed, then apply following changes to the variable  */

[data-theme="dark"] {
    --colour-bck: #222;
    --colour-font: #FFFAFA;
    transition-duration: 1s;
}


/* Styling the DOM */

body {
    margin: 0
}

.container {
    height: 100vh;
    background-color: var(--colour-bck);
}

body {
    color: var(--colour-font);
}

a {
    text-decoration: none;
    color: var(--colour-font);
    display: block;
    margin-top: 2em;
}

And the JavaScript:

/*
    darkMode switches to a dark/light mode view : body which renders the mode is fetch alongside data-theme holding the styles to render
    if the theme is dark, change it to light, which applies "data-theme = light" styles & vice-sersa
*/
console.log(localStorage)


function darkMode() {
    const container = document.getElementById('webPage');
    // const theme = container.getAttribute('data-theme');

    var dataTheme = container.getAttribute('data-theme');
    localStorage.setItem("theme", dataTheme);

    (localStorage.theme === 'dark') ? container.setAttribute('data-theme', 'light'): container.setAttribute('data-theme', 'dark');

}

Now, the thing is, I don't get any errors, and my value is saved into localStorage according to the console.log(). Hence my question, what did I do wrong?

Share Improve this question asked Jan 28, 2021 at 18:15 99Botch99Botch 431 silver badge9 bronze badges 3
  • The way you access local storage is incorrect: localStorage.theme. You should be using localStorage.getItem('theme'). – Terry Commented Jan 28, 2021 at 18:19
  • It looks like you're reading the theme from the document, saving it in local storage, then setting the other value to the document. Basically it doesn't matter what local storage is, you're just toggling it, but it's always based on the current state of the page. – Charlie Bamford Commented Jan 28, 2021 at 18:19
  • @Charles Bamford, does that mean I have to set the theme straight from my .js file, rather than the HTML one? – 99Botch Commented Jan 28, 2021 at 18:25
Add a ment  | 

1 Answer 1

Reset to default 4

I'm finding it hard to explain what you did wrong so I'll explain what I did to achieve what you want step-by-step.

const container = document.getElementById('webPage');

// This function will execute itself when the script is loaded
// https://developer.mozilla/en-US/docs/Glossary/IIFE
// you might want to wait for the whole page to load instead 
// https://stackoverflow./q/1033398/6398325
(function(){
    // Then set the 'data-theme' attribute to whatever is in localStorage      
    // the line below is mented because stackoverflow won't allow using localStorage on snippets
    // container.setAttribute('data-theme', localStorage.getItem('theme'));    
})();

function switchTheme() {

  // Check what is the current theme and get the opposite one
  const targetTheme = container.getAttribute('data-theme') === 'dark' ? 'light' : 'dark';

  // Set the attribute 'data-theme' to the targetTheme
  container.setAttribute('data-theme', targetTheme);

  // Save the targetTheme to the localStorage
  // the line below is mented because stackoverflow won't allow using localStorage on snippets
  // localStorage.setItem('theme', targetTheme);
}
main[data-theme="dark"] {
  color: white;
  background: #333;
}
<main id="webPage" onclick="switchTheme()">
  MyContent
</main>

You can ask in the ments if you need anything

Edit: I'll at least try to explain.

So, you said

I can't get my theme mode stored in local storage

But as you tested in the console.log it is actually saving the attribute value, you just didn't load the theme when the page was loaded, and that's what the function I've added is for.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745329412a4622808.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信