Abdelrahman Ashref
Abdelrahman Ashref

Reputation: 101

How to set 'local storage for attribute in jquery'?

I'm developing my own site and it supports multi themes for example (light & dark) theme when you click on option it apply theme and no problem to face but when you reload page you have then to choose theme again.

I've tried to fix that by adding key and value for local storage and I saw a lot of tutorials about it and no progress.

HTML Code

jQuery Code

$('.mode-toggler').click(function() {

    // Change attribute of css default theme by checking for statements with href attribute contains view keyword
    $("link[href*='view']").attr("href", $(this).attr("data-value");

});

Upvotes: 1

Views: 1620

Answers (1)

Sudipto Roy
Sudipto Roy

Reputation: 1046

So firstly you need to set in localstorage, the user selected theme:

$('.mode-toggler').click(function() {

    // Change attribute of css default theme by checking for statements with href attribute contains view keyword
    $("link[href*='view']").attr("href", $(this).attr("data-value"));

    // set localstorage
    localstorage.setItem("selectedTheme",  $(this).attr("data-value"));

});

And when you load the webpage next time, you will have to check for selectedTheme even before your page has loaded. Just include this script in you head tag.

<script>
var link = document.createElement('link');
link.rel = 'stylesheet';
link.href = localstorage.getItem("selectedTheme") || "view/light-view.css";
document.head.appendChild(link);
</script>

But I am afraid that this might lead to a flicker because at first, the raw html(without CSS) will get painted in your browser and then the whole of CSS gets inserted and DOM repaints with CSS. You can solve this by removing theme related CSS in a separate file(say darktheme.css) and put all other CSS in a constant css file(styles.css). While the page loads, load it with styles.css and load the *theme.css through script tag.

Upvotes: 2

Related Questions