'use strict'
const switcher = document.querySelector('.btn');
console.log(switcher);
switcher.addEventListener('click', function() {
document.body.classList.toggle('dark-theme');
let className = document.body.className;
if (className == "light-theme") {
this.textContent = "Dark";
}
else {
this.textContent = "Light";
}
});
Not sure how the toggle works. How is when I click the button the background changes back to the light-theme when the script doesn't even specify to change back to light-theme?
It's the document.body.classList.toggle('dark-theme');.
If that class exists, it is removed. If that class doesn't exist, it is added.
Your button changes the HTML from
<body class="light-theme">
to
<body class="light-theme dark-theme">
and back again.
Using CSS rules, if two rulesets with the same specificity are declared, and one is declared below the other, the one below will take precedence if both apply to an element. So
.light-theme {
/* rules */
}
.dark-theme {
/* rules */
}
will mean that if an element has dark-theme and light-theme, dark-theme's rules will override any duplicate styles applied by light-theme.
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Theme</title>
</head>
<body class="light-theme">
<div>
<button type="button" class="btn">Dark</button>
</div>
<script type="text/javascript">
'use strict'
const switcher = document.querySelector('.btn');
console.log(switcher);
switcher.addEventListener('click', function() {
document.body.classList.toggle('dark-theme');
document.body.classList.toggle('light-theme');
let className = document.body.className;
if (className == "light-theme") {
this.textContent = "Dark";
}
else {
this.textContent = "Light";
}
});
</script>
</body>
</html>
Related
I want to understand how this works. In the HTML is used the onclick="changeColor(this)" to communicate with the js. But if I change the word this in the HTML the code stops working. Why?
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="styles.css">
<link rel="script" href="script.js">
<title>Tente vocĂȘ</title>
</head>
<body>
<div onclick="changeColor(this)" style="background-color: blue;">
Me aperte para mudar de cor!
</div>
<script src="script.js"></script>
</body>
</html>
JS:
function changeColor(element) {
var currentColor = element.style.backgroundColor;
if (currentColor == "red") {
element.style.backgroundColor = "green";
}
else {
element.style.backgroundColor = "red";
}
}
this is a javascript keyword, that refers to the element (the div) in this case. If you change it, the div won't be passed to the function, therefore you won't be able to access it and change the background-color.
this is a complex topic in JS. the answer of philale would satisfies but if you want to know more about this I suggest reading this article.
gentle-explanation-of-this-in-javascript
this is a reference to the element which is clicked. If you change that, you change what the element argument is in the function.
However, it's worth noting that the approach of using onclick inline event handlers is outdated and no longer good practice. The better approach is to use unobtrusive event handlers, contained in the JS logic directly:
document.querySelectorAll('div').forEach(div => {
div.addEventListener('click', changeColor);
});
function changeColor(event) {
const element = event.target;
var currentColor = element.style.backgroundColor;
if (currentColor == "red") {
element.style.backgroundColor = "green";
} else {
element.style.backgroundColor = "red";
}
}
div {
background-color: blue;
}
<div>
Me aperte para mudar de cor!
</div>
Alternatively to using this it is possible to pass in the event of the click, handy when more information should be passed to the function. Change in HTML: onclick="changeColor(event)"
function changeColor(event) {
let element = event.currentTarget
var currentColor = element.style.backgroundColor;
if (currentColor == "red") {
element.style.backgroundColor = "green";
}
else {
element.style.backgroundColor = "red";
}
}
If you do not want to pass the event, it can be done like this in Javascript:
function changeColor() {
let element = this.changeColor.caller.arguments[0].currentTarget
var currentColor = element.style.backgroundColor;
if (currentColor == "red") {
element.style.backgroundColor = "green";
}
else {
element.style.backgroundColor = "red";
}
}
I'm trying to create a simple toggle switch to add a new class to the body tag. By default the page is red. By clicking the button the page is toggled between red and blue.
Here's the code I have so far - the Switch Colour button would then change the body class tag to blue
<body>
<p>Click the button to change the colour of page</p>
<button onclick="myFunction()">Change background colour</button>
<script>
function myFunction() {
var element = document.body;
element.classList.toggle("blue");
}
</script>
</body>
The CSS bit
body {
background-color: red;
color: white;
}
body.blue {
background-color: blue;
}
The bit I'm struggling with is to keep the settings when I refresh the page or move to another page. Is there a way to store this via Local Storage and javascript?
Thanks in advance,
Brian
For a more dynamic solution (what happens if you have more than two colors?), I would instead go with a CSS variable, where the default color is red. Stack Overflow doesn't allow reading from localStorage, so I will comment out that code, and instead use a variable for demo purposes.
I do think the code is self-explanatory.
const BACKGROUND_KEY = 'background';
var forDemoPurposeOnly = '';
function myFunction() {
let isBlue = readFromLocalStorage(BACKGROUND_KEY) == 'blue';
let color = (isBlue) ? 'red' : 'blue';
setBackgroundColor(color);
}
function setBackgroundColor(color) {
let root = document.documentElement;
root.style.setProperty('--user-selected-background', color);
setInLocalStorage(BACKGROUND_KEY, color);
}
function readFromLocalStorage(key) {
return forDemoPurposeOnly;
// return localStorage.getItem(key);
}
function setInLocalStorage(key, value) {
forDemoPurposeOnly = value;
// localStorage.setItem(key, value);
}
:root {
--background-color: var(--user-selected-background, red); /* defaults to 'red' */
}
body {
background-color: var(--background-color);
}
<body onload="setBackgroundColor(readFromLocalStorage('background'))">
<p>Click the button to change the colour of page</p>
<button onclick="myFunction()">Change background colour</button>
</body>
The local storage API is super simple to use. localStorage is available as a global in the browser, you can store a string value with a key and then retrieve the value with the key.
function myFunction() {
var element = document.body;
element.classList.toggle("blue");
var background = localStorage.getItem('background')
if (background === 'blue') {
localStorage.setItem('background', 'red')
} else {
localStorage.setItem('background', 'blue')
}
}
(function() {
var background = localStorage.getItem('background')
if (background === 'blue') {
document.body.classList.add(background)
}
})()
So I have a bit of script for toggling between light and dark modes on my site. The dark mode is the default. Problem is, whenever the light mode is toggled on, with every page load it flickers to the dark mode for just a second before loading the light mode. I would really like it to not do this and super appreciate any help you all can give. Thanks in advance!
My Code is as follows:
if (localStorage['blackout']) {
if (Number(localStorage['blackout']) == 1) {
$('BODY').addClass('blackout');
} else {
$('BODY').removeClass('blackout');
}
} else {
localStorage['blackout'] = 0;
$('BODY').removeClass('blackout');
}
$('BODY').show();
$('#boToggle').on('click', function(){
if (Number(localStorage['blackout']) == 0) {
localStorage['blackout'] = 1;
$('BODY').addClass('blackout');
} else {
localStorage['blackout'] = 0;
$('BODY').removeClass('blackout');
}
});
Put your JS (the part reading from local storage and applying the class) in the <head> section, and add the class to the <html> tag, so that it get executed before the body is parsed and displayed.
You can try it with this simple working demo:
<html>
<head>
<script>
// Do this before the body gets parsed
if (localStorage.getItem('darkmode') === '1') {
document.documentElement.classList.add('darkmode');
}
</script>
<style>
.darkmode body { background: #222; }
.darkmode .light-only { display: none; }
html:not(.darkmode) .dark-only { display: none; }
</style>
</head>
<body>
<button id="darkToggle">
Switch to
<span class="dark-only">light</span>
<span class="light-only">dark</span>
mode
</button>
<script>
document.querySelector('#darkToggle').addEventListener('click', function() {
var wasDarkMode = localStorage.getItem('darkmode') === '1';
localStorage.setItem('darkmode', wasDarkMode ? '0' : '1');
document.documentElement.classList[wasDarkMode ? 'remove' : 'add']('darkmode');
});
</script>
</body>
</html>
So basically I want to make a dark mode switcher for my website. I have a small script for start. It basically toggle the CSS style. But if I leave or refresh the page the style won't stay obviously...
<style>
.mystyle {
color:red !important;
background-color: black !important;
}
</style>
<script>
function init(){
var element = document.body;
element.classList.toggle("mystyle");
}
</script>
So my goal is to make this toggle button stay on its current state throughout the whole site even after refresh or change page...
A simple approach would be to save the state in localStorage, and when loading the page toggle the class according to its value.
Here is how you could implement it:
<style>
.dark-mode {
color: red;
background-color: black;
}
</style>
<body>
<button onclick="toggleMode()">Switch Mode</button>
</body>
<script>
const body = document.body;
if (localStorage.mode === 'dark') {
body.classList.add("dark-mode")
};
function toggleMode() {
body.classList.toggle("dark-mode");
localStorage.setItem(
'mode', localStorage.mode === 'light' || localStorage.mode === undefined ? 'dark' : 'light'
);
}
</script>
try removing and adding classes using add() and remove() functions, the following code may work:
<script>
var onOff=false; //to check of the class is active or not
function init(){
var element = document.body;
if(onOff === false){
element.classList.add("mystyle");
onOff = true;
}eles{
element.classList.remove("mystyle");
onOff = false;
}
}
</script>
I have been trying to toggle the background-color property of a button onclick but the color only changes once and does not toggle back and forth. Below is the code.
function btnColor(btn, color) {
var property = document.getElementById(btn);
if (property.style.backgroundColor == "rgb(244,113,33)") {
property.style.backgroundColor=color;
}
else {
property.style.backgroundColor = "rgb(244,113,33)";
}
}
<input type="button" id="btnHousing" value="Housing" onclick="toggleLayer('transparent1');btnColor('btnHousing','rgb(255,242,0)');" />
A simple solution (JS, CSS and HTML in order).
You setup a class in CSS, then select the button (yes the JS could have been done in one line) and toggle the class.
var button1 = document.querySelector("button");
button1.addEventListener("click", function() {
document.body.classList.toggle("colorred");
});
.colorred {
background-color: red;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Change color to background</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" media="screen" href="main.css" />
</head>
<body>
<button>Click me!</button>
<script src="main.js"></script>
</body>
</html>
The problem you're having is that the background-color of an element is reported differently in browsers, either rgb, rgba (with, or without, spaces) in hex or in HSL...
So the button will likely never satisfy the if condition, meaning it will always go to the else.
With that in mind, I'd suggest using a class-name to keep track of the un/toggled state:
function btnColor(btn, color) {
var property = document.getElementById(btn);
if (property.className !== 'toggled') {
property.style.backgroundColor=color;
property.className = 'toggled'
}
else {
property.style.backgroundColor = "rgb(244,113,33)";
property.className = '';
}
}
JS Fiddle demo.
Of course, if we're using the class of the element, we might as well use CSS to style the element:
function btnColor(btn) {
var property = document.getElementById(btn);
if (property.className !== 'toggled') {
property.className = 'toggled'
}
else {
property.className = '';
}
}
With the CSS:
#btnHousing {
background-color: rgb(255,242,0);
}
#btnHousing.toggled {
background-color: rgb(244,113,33);
}
JS Fiddle demo.
The previous JavaScript could be simplified (using the same CSS) to:
function btnColor(btn) {
var property = document.getElementById(btn);
property.className = 'toggled' == property.className ? '' : 'toggled';
}
JS Fiddle demo.