Change page backgrounds. LocalStorage - javascript

How to make sure that when you change the background color from the in the same tab, the background color would be changed in the other? Now the background color changes when the page is reloaded. I want to do that when digging the two identical tabs, and update one of them would have changed the background and the other.
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Untitled</title>
<style>
html, body {
height: 100%;
}
body {
margin: 0;
padding: 0;
display: flex;
align-items: center;
justify-content: center;
}
.bg-1 {
background: chocolate;
}
.bg-2 {
background: aqua;
}
.bg-3 {
background: grey;
}
h1 {
color: white;
font-size: 3em;
}
</style>
</head>
<body>
<h1>Change the background color of the page when you reload.</h1>
<script>
var body = document.body,
currentStyle = +localStorage.currentStyle || 0;
window.addEventListener('load', function() {
body.classList.add('bg-' + (currentStyle + 1));
localStorage.currentStyle = ++currentStyle % 3;
});
window.addEventListener('storage', function( event ) {
body.classList.remove('bg-' + event.oldValue);
body.classList.add('bg-' + (currentStyle + 1));
console.log(event.key);
});
</script>
</body>
</html>

This is the code you are looking for:
<script type="text/javascript">
var body = document.body;
window.addEventListener('load', function () {
var currentStyle = localStorage.getItem('currentStyle'),
newStyle=1;
if (currentStyle !== null) {
newStyle = currentStyle % 3 + 1;
}
body.classList.add('bg-' + newStyle);
localStorage.setItem('currentStyle', newStyle);
});
window.addEventListener('storage', function (event) {
var currentStyle = localStorage.getItem('currentStyle');
body.classList.remove('bg-' + event.oldValue);
body.classList.add('bg-' + currentStyle);
});
</script>

Related

why grid cells wont go below 32px width and height?

im trying to make static grid with a button that can change number of boxes in it (from 16x16 to 64x64 and anything between). Grid is 40rem x 40rem, when i try to change manually number of boxes in makeGrid() function it works fine up to 20 (boxes change size accordingly), but anything above 20 stays the same size and gets cutoff from my grid. If there is no grid css overflow property stated, grid width change depending on number of boxes but boxes themself won't shrink
my code:
size button is not working yet, grid size need to be changed mannualy in makeGrid function
const grid = document.getElementById('grid');
const size = document.getElementById('size');
const eraser = document.getElementById('eraser');
const color = document.getElementById('color');
const gridBorder = document.getElementById('grid-borders');
const clear = document.getElementById('clear');
// grid
function makeGrid(number) {
number = number || 16;
let cellWidth = 40 / number + 'rem';
let cellHeight = 40 / number + 'rem';
grid.style.gridTemplateColumns = `repeat( ${number}, 1fr)`;
grid.style.gridTemplateRows = `repeat(${number}, 1fr)`;
for (let i = 0; i < number * number; i++) {
let cell = document.createElement('div');
grid.appendChild(cell).id = 'box';
cell.classList.add('border');
cell.classList.add('box');
cell.style.backgroundColor = 'white';
cell.style.width = cellWidth;
cell.style.height = cellHeight;
}
size.textContent = `${number} x ${number}`;
}
makeGrid();
// drawing on hover
color.addEventListener('click', function () {
grid.addEventListener('mouseover', function (e) {
e.target !== grid ? (e.target.style.backgroundColor = 'black') : null;
});
});
function changeColor(event) {
event.target.style.backgroundColor = 'black';
}
// erase functionality
eraser.addEventListener('click', function () {
grid.addEventListener('mouseover', function (e) {
e.target !== grid ? (e.target.style.backgroundColor = 'white') : null;
});
});
// grid borders
const allBoxes = document.querySelectorAll('.box');
gridBorder.addEventListener('click', function () {
allBoxes.forEach((box) => {
box.classList.toggle('no-border');
box.classList.toggle('border');
});
});
// clear button
clear.addEventListener('click', function () {
allBoxes.forEach((box) => {
box.style.backgroundColor = 'white';
});
});
// size button
// size.addEventListener('click', function () {
// let number = prompt(`Enter grid size less or equal to 100`);
// if (number !== Number.isInteger()) {
// return;
// } else if (number > 100) {
// number = prompt(`Enter grid size greater or equal to 100`);
// }
// });
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
height: 100vh;
background-color: aquamarine;
}
#grid {
display: grid;
justify-content: center;
border: 1px solid #ccc;
width: 40rem;
height: 40rem;
min-width: 0;
min-height: 0;
overflow: hidden;
}
.box {
padding: 1em;
}
#title {
display: flex;
align-items: flex-end;
justify-content: center;
height: 180px;
}
#container {
display: flex;
height: 60%;
width: 1259px;
align-items: flex-start;
justify-content: flex-end;
gap: 20px;
padding-top: 20px;
}
#menu {
display: flex;
flex-direction: column;
gap: 10px;
}
.border {
outline: 1px solid black;
}
.no-border {
outline: none;
}
.black-bg {
background: black;
}
.white-bg {
background: white;
}
<!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" />
<title>Etch-a-Sketch</title>
<link rel="stylesheet" href="style.css" />
<script src="script.js" defer></script>
</head>
<body>
<div id="title">
<h1>Etch-a-Sketch</h1>
</div>
<main id="container">
<div id="menu">
<button id="size"></button>
<button id="color">Color</button>
<button id="eraser">Eraser</button>
<button id="clear">Clear</button>
<button id="grid-borders">Grid Borders</button>
</div>
<div id="grid"></div>
</main>
</body>
</html>
"Why won't my grid cells go below 32px?" - have you checked your padding (hint: 32px is exactly equal to 2 * 16px which in turn is exactly equal to your padding of 1em with most browsers implementing a default font-size of 16px). –
David Thomas
box padding was set to 1em which caused my problem, after deleting it my grid worked as intended

How to set the window's Y middle to element's Y middle?

I have created a button which should shift the window's Y to "BOX - 5" div's Y middle through onclick. So in other words I want to set the "Box - 5" div in the middle of the window. I have tried many methods using window.scrollTo and using elements.innerHeight/2, but I still cannot center the element to the middle of the window/screen. Please Help.
I wish to only use Javascript, but if its not possible with it then I would accept jQuery script.
index.html:
window.onbeforeunload = function () {
this.scrollTo(0, 0);
}
var content = document.getElementById("content"),
current = 0;
for (var y=0;y<10;y++) {
var box = document.createElement("div");
box.id = "box";
box.innerHTML = "Box - " + (y+1);
content.appendChild(box);
}
document.querySelector("BUTTON").onclick = function() {
var box_5 = document.querySelectorAll("#box")[4];
/*
NEED HELP HERE
*/
}
body {
margin: 0;
}
#box {
position: relative;
height: 500px;
width: 100%;
margin: 5% auto 5% auto;
color: black;
background-color: skyblue;
border: black 1px solid;
font-size: 50px;
text-align: center;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<button>CLICK TO SET THE WINDOW'S Y MIDDLE TO (BOX 5)'s Y MIDDLE</button>
<div id="content"></div>
</body>
</html>
Updated your snippet as below. You can use DOM element property offsetTop to check its Y position and use window.scroll to scroll the view to that element. Another sidenote, it's better to not assign the same id to multiple elements, so I change the id property to class and added identifier _{index} for the class name.
window.onbeforeunload = function () {
this.scrollTo(0, 0);
}
var content = document.getElementById("content"),
current = 0;
for (var y=0;y<10;y++) {
var box = document.createElement("div");
box.className += "box _" + (y+1);
box.innerHTML = "Box - " + (y+1);
content.appendChild(box);
}
document.querySelector("BUTTON").onclick = function() {
var box_5 = document.querySelectorAll(".box._5")[0];
if (box_5) {
// scroll the window view to the element
window.scroll({
top: box_5.offsetTop,
behavior: 'smooth',
})
}
}
body {
margin: 0;
}
.box {
height: 500px;
width: 100%;
margin: 5% auto 5% auto;
color: black;
background-color: skyblue;
border: black 1px solid;
font-size: 50px;
text-align: center;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<button>CLICK TO SET THE WINDOW'S Y MIDDLE TO (BOX 5)'s Y MIDDLE</button>
<div id="content"></div>
</body>
</html>

How can I create multiple progress bars using a for loop?

I've been playing around with the code below and using it to create a progress bar that responds to a certain type of data input. The data I'm using comes in the form of an array but I've noticed that the code only creates one progress bar.
How could I embed this within my for loop so that it creates a separate progress bar for each item in the array?
function move() {
var elem = document.getElementById("myBar");
var width = 0;
var id = setInterval(frame, 2000);
function frame() {
if (width >= 100) {
clearInterval(id);
} else {
width=width + 10;
elem.style.width = width + '%';
elem.innerHTML = ((100 - width)/10) + ' mins';
}
}
}
move();
#myProgress {
width: 80%;
background-color: #ddd;
horizontal-align: center;
}
#myBar {
width: 0%;
height: 30px;
background-color: #4CAF50;
text-align: center;
line-height: 30px;
color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
</head>
<body>
<div id="myProgress">
<div id="myBar"></div>
</div>
</body>
Here is the link to what I'm working on: My Workspace
Side Note: I've been trying to get the progress bar to be centered on the page with a margin: 200px on either side. The margin attribute in my CSS doesn't seem to be doing this and only applying the margin to the left but not to the right - where am I going wrong with this?
Try this
<html>
<style>
#myProgress {
width: 100%;
background-color: #ddd;
}
.myBar {
width: 10%;
height: 30px;
background-color: #4CAF50;
text-align: center;
line-height: 30px;
color: white;
}
</style>
<body>
<div id="myProgress">
</div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<script>
$(document).ready(function(){
var progressbars="";
var i;
for (i = 1; i <=10; i++) {
progressbars+="<div class='myBar' style='width:"+i+"%'"
+ " id='myBar"+i+"px'"
+">"+i+"%"+"</div><br/>";
}
$("#myProgress").html(progressbars);
});
</script>
</html>
Using Javascript Only
Just replace previous script with this
<script>
window.onload=function(){
var progressbars="";
var i;
for (i = 1; i <=10; i++) {
progressbars+="<div class='myBar' style='width:"+i+"%'"
+ " id='myBar"+i+"px'"
+">"+i+"%"+"</div><br/>";
}
document.getElementById("myProgress").innerHTML=progressbars;
}
This will generate
I see that you have included bootstrap 4
In that case you can create progress bars with Bootstrap
var progressbars="";
for (var i = 1; i <=10; i++) {
progressbars+='<div class="progress">'
+'<div class="progress-bar" role="progressbar" style="width: '+i+'%" aria-valuenow="'+i+'" aria-valuemin="0" aria-valuemax="100">'+i+'%</div>'
+'</div>';
}
document.querySelector(".feefo").innerHTML=progressbars;
And it looks a lot nicer :)

How to create smooth and goodlooking slightly text?

I want to create a text that can be shifted for long title.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style>
#abc {
position: relative;
overflow: hidden;
width: 200px;
height: 100px;
}
#def {
position: absolute;
font-size: 2em;
color: #000;
margin: 0;
width: 400px;
}
</style>
<script>
var teks = null;
function geser() {
var left = 0;
function frame() {
left--; // update parameter
teks.style.left = left + 'px';
if (left == -200) {
clearInterval(id);
setTimeout(function() {
runningtext();
}, 2000);
}
}
var id = setInterval(frame, 40)
}
function runningtext() {
teks = document.getElementById("def");
teks.style.left = '0px';
setTimeout(function() {
geser();
}, 2000);
}
window.onload = runningtext;
</script>
</head>
<body>
<div id="abc">
<p id="def">Cihampelas Demin Center</p>
</div>
</body>
</html>
The script is successfully work with 1 line.
Output :
Cihampelas Demin Center
Question is :
Is there another way to print 1 line without #def { width:400px; }?
(When I try #def { display:inline; }
Output :
Cihampelas
Demin Center
)
When object's left = -200px, I want to reserve in same way, but I have no idea.

Set font-weight back if another li is selected

On another question I asked if I could set the font-weight to bold on a text element when that text is selected. This has been completed much to the avail of #Eric ! But currently, when you click a text, you can happily click another one and both of the text will be bold.
How can I prevent more than one text element from being bold?
Here is my code on JSFiddle: http://jsfiddle.net/6XMzf/ or below:
CSS:
html,body {
margin: 0;
padding: 0
}
#background {
width: 100%;
height: 100%;
position: absolute;
left: 0px;
top: 0px;
z-index: 0;
color: white;
}
.stretch {
width:100%;
height:100%;
}
.navigationPlaceholder {
width:100px;
height: 400px;
left: 100px;
top: 100px;
position: absolute;
}
#navigation {
background-color: #000000;
}
#navigationText ul {
font-family: "Yanone Kaffeesatz";
font-weight: 100;
text-align: left;
font-size: 25px;
color: #b2b2b2;
left: 25px;
top: 50px;
position: absolute;
line-height: 40px;
list-style-type: none;
}
.noSelect {
-moz-user-select: none; /* mozilla browsers */
-khtml-user-select: none; /* webkit browsers */
}
HTML:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>Max Kramer | iOS Developer</title>
<link rel="stylesheet" type="text/css" href="css/style.css" />
<link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Yanone+Kaffeesatz" />
</head>
<body>
<div id="background" />
<div id="navigation" class="navigationPlaceholder">
<div id="navigationText">
<ul>
<li>iOS</li>
<li>Blog</li>
<li>About</li>
<li>Contact</li>
</ul>
</div>
</div>
</div>
<script type="text/javascript">
var nav = document.getElementById('navigationText');
var navItems = nav.getElementsByTagName('li');
for (var i = 0; i < navItems.length; i++) {
navItems[i].addEventListener('click', function() {
this.style.fontWeight = '400';
}, false);
}
</script>
</body>
</html>
If you don't have a selector engine handy like jQuery and really have to do this in plain Javascript, I would do it like this:
function addClass(elem, className) {
if (elem.className.indexOf(className) == -1) {
elem.className += " " + className;
}
}
function removeClass(elem, className) {
elem.className = elem.className.replace(new RegExp("\\s*" + className), "");
}
var lastSelected = null;
function initNavClickHandler() {
var nav = document.getElementById('navigationText');
var navItems = nav.getElementsByTagName('li');
for (var i = 0; i < navItems.length; i++) {
navItems[i].addEventListener('click', function() {
addClass(this, "selected");
if (lastSelected) {
removeClass(lastSelected, "selected");
}
lastSelected = this;
}, false);
}
}
initNavClickHandler();
Then, add a CSS rule that controls the selected look:
.selected {font-weight: 800;}
This is a lot more flexible for styling because you can add as many CSS rules as you want to the .selected class to change/modify it without ever touching your code.
You can see it work here: http://jsfiddle.net/jfriend00/rrxaQ/
If you can use things like jQuery then this is a much simpler problem. Let me show you the jQuery solution for both highlighting and unhighlighting.
$("#navigationText li").click( function() {
$("#navigationText li").css("fontWeight", "100");
$(this).css("fontWeight", "400");
});
Now you can achieve the same thing yourself without jQuery. You either need to create a global that holds the currently bolded item and remove the fontWeight or just remove the fontWeight from all items (brute force).
//untested with global to store currently selected
var nav = document.getElementById('navigationText');
var activeItem = null;
var navItems = nav.getElementsByTagName('li');
for (var i = 0; i < navItems.length; i++) {
navItems[i].addEventListener('click', function() {
if (activeItem) {activeItem.style.fontWeight = '100'; }
this.style.fontWeight = '400';
activeItem = this;
}, false);
}
//sorry I don't feel like writing a brute force one for you!

Categories

Resources