Change site style / theme and store it in LocalStorage

0

I have a theme change system in my blog, however it has some problems, like, it can not change the style of a div.class added by jquery (addClass) or pseudo elements (after / before / active etc ) and it gets all disorganized !!

I'm looking for a new way to do this (OR ONE SOLUTION if it exists) and I'll love it if you give me suggestions ...

Simplified sample of my current system in JSFiddle: link

In it I show how it works, changing the style of the element, saving it in the localStorage, and the indifference when trying to change the theme of an 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));

Thank you! ;)

    
asked by anonymous 04.12.2018 / 05:50

1 answer

3

Your problem is simpler than it sounds ..

Basically where you put

.elemento:after[theme="claro"]

Should be

.elemento[theme="claro"]:after

You want to reach :after of .elemento when this element has the theme="claro" attribute and not the pseudo-element :after that has the theme="claro" / p>

Your code does not work in the Snipper here of StackOverflow, I think because of the localStorage ... But see the image

    
04.12.2018 / 11:30