Create "dark" function on the site!

Asked

Viewed 330 times

5

I am developing a website and wanted to implement that famous "dark" function so that the user can choose.

Searching and mining our dear internet, I managed to have a certain result, I created the button "Dark" and breaking the "Ligth".

Imagem dos botões

However, every time the page of refresh the site returns to the pattern (same white). My wish is to fix this function so that it is no longer altered. I’d like a little help from you masters!

Follow the code of what is already ready:

HTML

<body id=“bg”>
…
div>
<button onclick=“light()” type=“button” >Tema Light</button>
<button onclick=“dark()” type=“button” >Tema Dark</button>
</div>

Javascript

function dark()
{
document.getElementById(‘bg’).style.background=’#212121 center center no-repeat’;
}
function light()
{
document.getElementById(‘bg’).style.background=’#e6e6e6 center center no-repeat’;
}

4 answers

2

You can use cookies or the API of localStorage. In that answer, I will demonstrate how to use the localStorage to persist data through front-end.

const lightButton = document.querySelector('#light-theme-trigger');
const darkButton = document.querySelector('#dark-theme-trigger');

// Adicionamos os listeners:
lightButton.addEventListener('click', () => setTheme('light'));
darkButton.addEventListener('click', () => setTheme('dark'));

// Criamos a função que irá ficar responsável pela troca do tema:
function setTheme(themeName) {
  // Salvamos no localStorage:
  localStorage.setItem('site-theme', themeName);

  // E aqui você pode fazer o que quiser com o nome do tema,
  // como aplicar os estilos.
}

// Executamos a função sempre que a página é carregada, passando
// o tema salvo no `localStorage`. Note que usei o `light` como
// fallback caso nenhum estiver definido no storage.
setTheme(localStorage.getItem('site-theme') || 'light');

Basically, the localStorage has its methods to obtain and define a value (others also, which I will not quote here).

  • localStorage.getItem: Returns the stored value. If no, return null.
  • localStorage.setItem: Define a value. You must pass the key in the first argument and in the second, the value.

To learn more about the localStorage, consult:

Note: It is important to emphasize that it is not recommended to use the localStorage to store no important information, such as passwords or the like, since it can be easily accessed by the client through the developer’s tools.

  • Thank you very much Luiz from your way of view I could learn a little more! Tmj

1


I would do differently, using CSS classes and just a function to switch between themes. Just create in CSS the two classes, .dark and .light:

.dark{
   background: #212121 center center no-repeat;
}

.light{
   background: #e6e6e6 center center no-repeat;
}

On the buttons, you call the same function by passing as parameter the name of each class:

<button onclick="tema('light')" type="button" >Tema Light</button>
<button onclick="tema('dark')" type="button" >Tema Dark</button>

And the function takes the class name and adds body and creates the localStorage:

function tema(t){
   document.body.classList.add(t)
   localStorage.setItem("tema", t);
}

When loading the page, you check if the localStorage with the name tema has some value and adds the class in body with the value saved:

var ls = localStorage.getItem("tema");
if(ls) document.body.classList.add(ls);

In this way, the body will be with one of the two classes if the localStorage.getItem("tema") exist and have value. For example:

<body class="dark">

The advantage of putting a class in the body is that you can later, if you want, change other elements of the body, such as changing the color of the page text to white by adding color: #fff in class .dark:

.dark{
   background: #212121 center center no-repeat;
   color: #fff;
}

Only one Obs.: don’t need to put id on the tag body. Since the body is unique on the page, just use document.body, as I put it above.

  • Man this perfectly solved my problem, thank you very much, tmj

0

Guys, I posted this in another forum and a user called wldomiciano me gave the following solution:

No need to force refresh. I believe the problem is in the theme function().

In it you just add the new class, but it is important to remove the old class.

function tema(t){
  const ls = localStorage.getItem("tema");

  if(ls) document.body.classList.remove(ls);

  document.body.classList.add(t)
  localStorage.setItem("tema", t);
}

I believe that with the above passage you can solve this problem and use again <button> instead of <a>.

It really worked so I’m sharing it here with you ;-)

-1

Short observation: before the button I put

<a href="index.html">

So that there was always refresh on the site, because I noticed that when we clicked for example on the "dark" dps of the "light" and then on the "dark" dnv it did not store the third situation, but when it gave refresh he applied the color.

Browser other questions tagged

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