How to change style of multiple elements with a single script? - javascript

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>

Related

Why is the imagine not displayed while beeing "inline". js/html

I want to show and hide a picture by using one button. when it's clicked, the picture is displayed and a variable is set to 1. so that when you press the button the next time, the picture will be hidden again.
After the button is pressed, I console.log the value of set variable + if the picture is displayed or not. Console says that the Picture is "inline". But the picture is not on my screen.
I think all you need is the js function. If you need more information. just comment. thank's!
<script>
function showHideM(){
let open;
open = 0
if (open == 0){
open = 1;
document.getElementById("melmanId").style.display = "inline";
console.log(open)
console.log(document.getElementById("melmanId").style.display)
return;
}
if (open == 1){
open = 0;
document.getElementById("melmanId").style.display = "none";
}
}
</script>
You don't really need flags to maintain the state of the image's visibility. You can use classList's toggle method to toggle a class on/off or, in this case, visible/hidden, which makes things a little easier.
// Cache the elements, and add an event listener
// to the button
const img = document.querySelector('img');
const button = document.querySelector('button');
button.addEventListener('click', handleClick);
// Toggle the "hidden" class
function handleClick() {
img.classList.toggle('hidden');
}
.hidden { visibility: hidden; }
img { display: block; margin-bottom: 1em; }
button:hover { cursor: pointer; background-color: #fffff0; }
<img class="hidden" src="https://dummyimage.com/100x100/000/fff">
<button>Click</button>
Additional documentation
addEventListener
querySelector
Note: this will replace all the styles applied to 'melmanId'
<script>
let show = true;
function showHideM() {
show = !show;
if(show){
document.getElementById("melmanId").style.display = "inline";
}else{
document.getElementById("melmanId").style.display = "none";
}
}
</script>

CSS Toggle Switch to add a class to a DIV with local storage

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)
}
})()

How to stop light mode flickering to darker background on page load

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>

Add a style to html and body via onclick

I am having a problem with my hamburger menu, my background page scrolling when it is open. I noticed that if I add 'overflow: hidden' to the body and html, it fixes the problem. However, when I close the menu, the body is obviously still locked. How can I add javascript to cancel these styles from the body and html?
This is what I have tried:
<div class="navbar_toggle" onclick="nonscroll(this)">
<script>
function nonscroll(elem) {
document.body.style.overflow = "hidden";
document.html.style.overflow = "hidden";
}
</script>
When I click the button, I want these styles to apply. When I close the menu, I want them to disappear. Is there a very simple way to fix this?
Solution
Copy from this example, paste into your page:
function FixScrollToggle (node) {
var target = document.body;
function isClicked () {
return target.classList.contains('fixScrollToggle--on');
}
function freeze() {
target.classList.add('fixScrollToggle--on');
}
function unFreeze() {
target.classList.remove('fixScrollToggle--on');
}
function onClick (e) {
if (isClicked()) { return unFreeze(); }
return freeze();
}
node.addEventListener('click', onClick, false);
}
document.addEventListener('DOMContentLoaded', function () {
Array.prototype.slice.
call(document.querySelectorAll('[data-apply-fix]')).
forEach(FixScrollToggle);
});
.fixScrollToggle--on {
overflow: hidden;
background-color: #c00;
}
<div class="navbar_toggle" data-apply-fix>Click me</div>
It's not the most easy way, but it's a clean and relatively easy way. Just put the JS code into a <script> tag in your page.
Explanation
This code works by adding a click eventlistener to each HTML element which has a data-apply-fix attribute set. This way, you can attach the same behaviour to multiple elements on your page.
The behaviour of manipulating the CSS is entirely done with the CSS class fixScrollToggle--on. This way, you have a very clean separation of concerns.
In nonscroll() function, you need to do two things:
Check if nav is hidden or shown.
When you know the nav visibility, you can update style for body and html.
<div class="navbar_toggle" onclick="nonscroll(this)">
<script>
function nonscroll(elem) {
// check if navbar is hidden or shown
// if nav is hidden: "body overflow is 'hidden'"
// else "body overflow is 'static'"
var nav = document.getElementsByClassName("navbar_toggle");
var nav_hidden = (window.getComputedStyle(nav[0]).visibility === "hidden")
if(nav_hidden) {
document.body.style.overflow = "hidden";
document.html.style.overflow = "hidden";
} else {
document.body.style.overflow = "static";
document.html.style.overflow = "static";
}
}
</script>
Simple ways to do that is using toggle class on click listener, as your code above it could:
var toggle = document.getElementsByClassName('navbar_toggle')[0];
var html = document.getElementsByTagName('html')[0];
var body = document.getElementsByTagName('body')[0];
var all = [html,body];
toggle.addEventListener( 'click', function() {
for ( var i=0; i < all.length; i++ ) {
all[i]classList.toggle('is-active');
}
});
Then ur css should be:
html, body {
overflow: auto;
}
.is-active {
overflow: hidden;
position: fixed; // prevent body scrolling for safari and ios
}

Toggle Visibility (Automatically causing one div element to hide when another is rendered visible)

Essentially what I am trying to do is create a website that has all of its content on the home page but only has some of the content visible at any one time. The way I read to do this is through toggling visibility.
The problem I am having is that: Assume the home page, when you first visit the website is blank (the way I want it to be). Lets say you click on the "about us" link. All of a sudden the about us section becomes visible (the way I want it to be). Now the problem that I have come across is when I know lets say click on the "products" link, I want the "products" content to become visible and the "about us" content to become invisible again. (Essentially creating the illusion of opening a new page within the same page).
Here is the code I have come up with so far. I can make certain div elements visible and invisible (onclick) but I can't figure out how to make sure only one div element is visible at any one time.
<script type="text/javascript">
function toggleVisibility() {
document.getElementById("about").style.display = "";
if(document.getElementById("about").style.visibility == "hidden" ) {
document.getElementById("about").style.visibility = "visible";
}
else {
document.getElementById("about").style.visibility = "hidden";
}
}
</script>
<script type="text/javascript">
function toggleVisibility1() {
document.getElementById("products").style.display = "";
if(document.getElementById("products").style.visibility == "hidden" ) {
document.getElementById("products").style.visibility = "visible";
}
else {
document.getElementById("products").style.visibility = "hidden";
}
}
</script>
The links to make the JavaScript work looks like this:
< href="#" onclick="toggleVisibility();">About
< href="##" onclick="toggleVisibility1();"> Products
here is another, simple function
<script type="text/javascript">
function toggle_visibility(id) {
var e = document.getElementById(id);
if(e.style.display == 'block')
e.style.display = 'none';
else
e.style.display = 'block';
}
</script>
if you click here, #foo will change visibility
<div id="foo">blablabla</div>
Without jQuery, you would want to do something like this:
<style type="text/css">
.content {
display: none;
}
#about {
display: block;
}
</style>
<script type="text/javascript">
function toggleVisibility(selectedTab) {
// Get a list of your content divs
var content = document.getElementsByClassName('content');
// Loop through, hiding non-selected divs, and showing selected div
for(var i=0; i<content.length; i++) {
if(content[i].id == selectedTab) {
content[i].style.display = 'block';
} else {
content[i].style.display = 'none';
}
}
}
</script>
About
Products
<div id="about" class="content">About stuff here</div>
<div id="products" class="content">Product stuff here</div>
Example here: http://jsfiddle.net/frDLX/
jQuery makes this much easier, but if you are beginning with JavaScript, sometimes you want to see the programmatic code, so you can tell what is going on.
This is exactly what jquery makes easier. Take this very simple example of what you're trying to achieve:
<style type="text/css">
.section {
display: none;
}
</style>
<script type="text/javascript">
function toggleVisibility(newSection) {
$(".section").not("#" + newSection).hide();
$("#" + newSection).show();
}
</script>
About
Products
<div id="about" class="section">about section</div>
<div id="products" class="section">products section</div>
Simple solution is like this:
<script type="text/javascript">
function toggleVisibility(divid) {
if (divid="about"){
document.getElementById("about").style.visibility = "visible";
document.getElementById("products").style.visibility = "hidden";
}
else if (divid="products")
{
document.getElementById("products").style.visibility = "visible";
document.getElementById("about").style.visibility = "hidden";
}
}
</script>
< href="#" onclick="toggleVisibility('about');">About
< href="##" onclick="toggleVisibility1('products');"> Products
use CSS display: property
element disappear
document.getElementById("products").style.display = "none";
element appear and is displayed as block (default for div)
document.getElementById("products").style.display = "block";
I posted sample code here: jQuery: menus appear/disappear on click - V2
PS
Here you can find nice examples about differences between display and visibility: http://wiw.org/~frb/css-docs/display/display.html

Categories