Night Mode html css js

Asked

Viewed 1,864 times

1

Guys, I found an API on the internet of a Switcher that changes the theme of the page by clicking the button, but I’m not getting other Ivs to change color too, just the body that changes color, please help me. i tried to change the theme of div div teste1, but without success, please, if you try to help, try to make the theme remain while refreshing/reloading the page, please help me please.

function applyTheme (theme) {
    "use strict"
	document.getElementById("mypage").className = theme;
	localStorage.setItem ("theme", theme);	
}

function applyDayTheme () {
    "use strict"

	applyTheme("day");

}

function applyNightTheme() {
        "use strict"
	applyTheme("night");

}

function addButtonLestenrs () {
        "use strict"

document.getElementById("b1").addEventListener("click", applyDayTheme);
document.getElementById("b2").addEventListener("click", applyNightTheme);

}

function initiate(){
        "use strict"

	if(typeof(localStorage)===undefined)
		alert("the application can not be executed properly in this browser");
	else{
		if(localStorage.getItem("theme")===null)
			applyDayTheme();
		else
			applyTheme(localStorage.getItem("theme"));
		
	}
	addButtonLestenrs();
}

initiate();
.day{
color:black;
background-color:rebeccapurple;

}
.night{
color:white;
background-color:black;
}

.teste1{
    background-color: blue;
    width: 250px;
    height: 80px
}
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<link rel="stylesheet" href="Estilos.css">
	
</head>
<body id="mypage" >
	<h1>Choose a theme</h1>
	<button id="b1">Theme day</button>
	<button id="b2">Theme night</button>
	
	<p> This is an example of use of HTML5 storage API </p>

   <div class="teste1" >
    in
</div>
   
   
    <script type="text/javascript" src="change-theme.js"></script>
</body>
</html>

1 answer

0


The localSorage is working properly, but to change the styles of the div .teste1, you need to create a class for this div based on the class of each theme, for example:

/* ESTILOS QUANDO A CLASSE DO BODY FOR .day */
.day .teste1{
    background-color: blue;
    width: 250px;
    height: 80px
}

/* ESTILOS QUANDO A CLASSE DO BODY FOR .night */
.night .teste1{
    background-color: red;
    width: 250px;
    height: 80px
}

whereas .teste1 is the direct son of body.

Or you can create classes only with whatever is different between themes:

.teste1{
    width: 250px;
    height: 80px
}

.day .teste1{
    background-color: blue;
}

.night .teste1{
    background-color: red;
}

Browser other questions tagged

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