简体   繁体   中英

I can't apply the dark theme without showing the light theme first in a web app made with pure html, css and javascript

how are you?, I have a web app and I made a dark and light theme by integrating and modifying examples from other sources, I can currently can save the current applied theme in local storage to have the theme applied when I change between pages in my app, the problem that I have is when I change between pages, if the current theme is the dark one allways the light theme is displayed firts and inmediatly the dark theme is applied.

Initially I had the html document like this

<html>
     <body class="tema-claro">
     ..........
     <div class="salir">
        button onclick="salir()">Salir</button>
    </body
    <script src=app.js type="text/javascript></script>
</html>

the javascript is the following

"use strict";
Aplica_Estado_Inicial();

function Cambia_Tema() {
    let tTema;
    const cambiador = document.querySelector('.tema-visual');
    document.body.classList.toggle('tema-claro');
    document.body.classList.toggle('tema-oscuro');
    document.body.style.transition = "1s ease"; //indicado por openAi
    localStorage.setItem("tema", document.getElementsByTagName("body")[0].className);
    const className = document.body.className;
    if(className == 'tema-claro') {
        tTema = 'Oscuro';
    }
    else if(className == 'tema-oscuro') {
        tTema = 'Claro';
    }
    document.getElementById("temVis").innerHTML = tTema;
    localStorage.setItem("textoTema", tTema);
    console.log(localStorage.getItem("textoTema"));
}

function Salir() {
.
.
.
}

function Aplica_Estado_Inicial() {
    if(localStorage.getItem("primeraCarga") === undefined) {
        localStorage.setItem("primeraCarga", true);
        document.body.className = "tema-claro";
        document.getElementById("temVis") = Oscuro;
    }
    if(!(localStorage.tema === undefined)) {
        document.body.className = localStorage.getItem("tema");
        document.getElementById("temVis").innerHTML = 
        localStorage.getItem("textoTema");
    }
}

the function function Cambia_Tema() is the function that changes the theme when I press a button, the function Aplica_Tema_Inicial() is the one that applies the actual theme to the newly loaded page but every time a new page of the app is loaded the light theme is loaded.

Trying to solve the problem I modified the Aplica_Estado_Inicial() to this way

function Aplica_Estado_Inicial() {
    if(localStorage.getItem("primeraCarga") === undefined) {
        localStorage.setItem("primeraCarga", true);
        document.body.className = "tema-claro";
        document.getElementById("temVis") = Oscuro;
    }
    else if(localStorage.getItem("primeraCarga") == true) {
        document.body.className = localStorage.getItem("tema");
        document.getElementById("temVis") = localStorage.getItem("textoTema");
    }
    if(!(localStorage.tema === undefined)) {
        document.body.className = localStorage.getItem("tema");
        document.getElementById("temVis").innerHTML = 
        localStorage.getItem("textoTema");
    }
}

to add a flag for the app to remember not to apply whatever initial on load theme that the app could have but it didn't help

and the html document to this way

<body onload="Aplica_Tema_Inicial()">
.
.
.
</body>

but this didn't work

my themes are in the following order in the CSS file

.tema-oscuro {
    --body-color: #161719;
    --grad-uno-color: #4d4d51;
    --grad-dos-color: #000101;
    --primary-color-light: #f6f5ff;
}

.tema-claro {
    --body-color: #e6e6d9;
    --grad-uno-color: #bbbbbb;
    --grad-dos-color: #4d4d51;
    --primary-color-light: #1e2027; 
}

So, if anyone can help me with this I'll be very grateful.

UPDATE 11/01, 3:10 pm

Apparently I could solve the problem by changing several things in my code, first in the javascript file I changed both Aplica_Estado_Inicial() and Cmabia_Tema() for variables with event listeners looking for clicks on both buttons, then I stop calling Aplica_Estado_Inicial() every time the javascript file is loaded on each page of my app.

In the html document I erased all the onclick events and gave an id to the body and all the buttons to relate them with the event listeners mentioned above, finally just at the following line of the oppening body tag I added a script tag and inside that tag I included a simple if that checks if a property called "tema" is not 'null', this property is the one that stores the actual theme being applied; if the condition is met then the theme is assigned to the class of the body.

Those changes makes all the pages to load without apply the light theme first. See the code bellow

html document:

<body class="tema-claro">
    <script>
        if(!(localStorage.getItem("tema") == null)) {
            document.body.classList = localStorage.tema;
        }
    </script>
    ....
    <div>
    .....
    </div>
    <div class="salir">
        <button id="bloquearSistema">Salir</button>
    </div>
</body
<script src="app.js" type="text/javascript"></script>
<noscript>Debe habilitar Javascript para ver el sitio completo</noscript>

of course all of that wrapped into the tag

the javascript file like follows

    "use strict";

    var estados = document.getElementById("temVis");
    estados.addEventListener("click", function() {
    let tTema;
    const cambiador = document.querySelector('.tema-visual');
    document.body.classList.toggle('tema-claro');
    document.body.classList.toggle('tema-oscuro');
    document.body.style.transition = "1s ease"; //indicado por openAi
    localStorage.setItem("tema", document.getElementsByTagName("body")[0].className);
    const className = document.body.className;
    if(className == 'tema-claro') {
        tTema = 'Oscuro';
    }
    else if(className == 'tema-oscuro') {
        tTema = 'Claro';
    }
    document.getElementById("temVis").innerHTML = tTema;
    localStorage.setItem("textoTema", tTema);
    console.log(localStorage.getItem("textoTema"));
});

var bloqueado = document.getElementById("bloquearSistema");
bloqueado.addEventListener("click", function() {
    var sHTTP = new XMLHttpRequest();
    sHTTP.open("GET", "no-permitido", true);
    sHTTP.send();
    setTimeout(function(){window.open("autenticar.html", "_self");}, 1000);    
});

I could solve the problem by changing several things in my code, first in the javascript file I changed both Aplica_Estado_Inicial() and Cmabia_Tema() for variables with event listeners looking for clicks on both buttons, then I stop calling Aplica_Estado_Inicial() every time the javascript file is loaded on each page of my app.

In the html document I erased all the onclick events and gave an id to the body and all the buttons to relate them with the event listeners mentioned above, finally just at the following line of the oppening body tag I added a script tag and inside that tag I included a simple if that checks if a property called "tema" is not 'null', this property is the one that stores the actual theme being applied; if the condition is met then the theme is assigned to the class of the body.

Those changes makes all the pages to load without apply the light theme first. See the code bellow

html document:

<body class="tema-claro">
    <script>
        if(!(localStorage.getItem("tema") == null)) {
            document.body.classList = localStorage.tema;
        }
    </script>
    ....
    <div>
    .....
    </div>
    <div class="salir">
        <button id="bloquearSistema">Salir</button>
    </div>
</body
<script src="app.js" type="text/javascript"></script>

<noscript>Debe habilitar Javascript para ver el sitio completo</noscript>

of course all of that wrapped into the tag <html>

the javascript file like follows

"use strict";

var estados = document.getElementById("temVis");
estados.addEventListener("click", function() {
let tTema;
const cambiador = document.querySelector('.tema-visual');
document.body.classList.toggle('tema-claro');
document.body.classList.toggle('tema-oscuro');
document.body.style.transition = "1s ease"; //indicado por openAi
localStorage.setItem("tema", document.getElementsByTagName("body")[0].className);
const className = document.body.className;
if(className == 'tema-claro') {
    tTema = 'Oscuro';
}
else if(className == 'tema-oscuro') {
    tTema = 'Claro';
}
document.getElementById("temVis").innerHTML = tTema;
localStorage.setItem("textoTema", tTema);
console.log(localStorage.getItem("textoTema"));
});

var bloqueado = document.getElementById("bloquearSistema");
bloqueado.addEventListener("click", function() {
    var sHTTP = new XMLHttpRequest();
    sHTTP.open("GET", "no-permitido", true);
    sHTTP.send();
    setTimeout(function(){window.open("autenticar.html", "_self");}, 1000);    
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM