Change the style/theme of the site and store it in Localstorage

Asked

Viewed 147 times

0

I have a theme change system on my blog, but it has some problems, like, it can’t change the style of a div.class added by jquery (addClass) or pseudo elements styles (after/before/active etc) and everything gets disorganized!!

I am looking for a new way to do this (OR A SOLUTION, if any) and I will love it if you give me suggestions...

Simplified sample of my current system in Jsfiddle: https://jsfiddle.net/ybocfr7n/1/

In it I show how it works, changing the style of the element, saving it in localStorage, and indifference when trying to change the theme of a . element:after.

HTML

<div class="elemento">Hello World!</div>

<div class="theme-toggle" data-theme="claro">Tema Claro</div>
<div class="theme-toggle" data-theme="escuro">Tema Escura</div>

CSS

/* tema escuro (original) */
.elemento { background-color: #212121 }
.elemento:after {
  content: '';
  position: absolute;
  border:  10px solid green;
  background-color: red;
}
/* tema claro - observe que o pseudo :after não altera */
.elemento[theme="claro"] { background-color: #CCCCCC }
.elemento:after[theme="claro"] {
  content: '';
  position: absolute;
  border: 20px solid orange;
  background-color: red;
}

jQuery

(function ($) {
var $temaclaro = $('.elemento');
var loadTheme = function () {
$temaclaro.attr('theme', localStorage.getItem('theme') || 'default');
};
$('.theme-toggle').click(function () {
localStorage.setItem('theme', $(this).data('theme'));
loadTheme();
});
loadTheme();
} (jQuery));

Thanks in advance!! ;)

  • Good morning! Dude, honestly there aren’t many alternatives... Vc can use . style (js) or . css(jquery) to change styles through some function

2 answers

3


Your problem is simpler than it looks..

Basically where you put

.elemento:after[theme="claro"]

Should be

.elemento[theme="claro"]:after

'Cause you want to hit the :after of .elemento when that element has the attribute theme="claro" and not the pseudo-element :after that has the attribute theme="claro" understands.

Your code does not work in the Snipper here from Stackoverflow, I think due to the localStorage... But see the image

inserir a descrição da imagem aqui

  • 1

    Boy, it never crossed my mind to try to put him in this position...

  • 1

    Thank you very much!!!

  • No problem, we are there to help rss.

0

Supplemented the question nowadays we can use css variables and change with javascript, example:

function trocarCor () {
  document.body.style.setProperty('--color-primary', 'green')
}
:root {
  --color-primary: red;
}

.color-primary {
  color: var(--color-primary) !important
}
<div class="color-primary">Testando</div>

<button onclick="trocarCor()">Trocar cor</button> 

Thus it is possible to have several custom themes and most important dynamics just by changing the value of the css variable.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.