Javascript - Change colour of div based on current colour - javascript

I am trying to change the background colour of a div based on it's current colour, via the click of a button.
For example, if the colour is cyan (#00ffff - it should change to yellow ('ffff00).
If the colour is yellow - it should change to magenta (#ff00ff).
If the colour is magenta - it should revert back to cyan.
I have managed to change the color to yellow from cyan, however I am not sure exactly how to write my if statement (assuming an if statement is the best way?) to change the colours based on the current colour.
function ColorFunction() {
if (light.getItem("backgroundColor") == '#00ffff') {
document.getElementById("light").style.backgroundColor = "#ffff00";
}
else
if (light.getItem("backgroundColor") == '#ffff00') {
document.getElementById("light").style.backgroundColor = "#ff00ff";
}
else
if (light.getItem("backgroundColor") == '#ff00ff') {
document.getElementById("light").style.backgroundColor = "00ffff";
}
}
.main {
width:250px;
color: #202020;
background-color: #d0d0d0;
}
.light {
width: 50px;
height: 50px;
background-color: #00ffff
}
#burn {
width: 150px;
font-style: italic;
}
#button {
font-style: bold;
width: 150px;
}
<h1>Disco Inferno</h1>
<div class="light" id="light">
div
</div>
<button onClick="ColorFunction()">Burn!</button>

Ok, lets start at the beginning here.
You have an element with the id light but that does not automatically become a variable you can use in javascript. Its easy enough to make it one:
var light = document.getElementById("light");
Then, i'm not even sure where you get getItem from - perhaps it was a guess - but its not a valid method on an HTMLElement
You could do this with light.style.backgroundColor - see the snippet below.
var colors = ["rgb(0, 255, 255)","rgb(255, 255, 0)","rgb(255, 0, 255)"];
function ColorFunction() {
var light = document.getElementById("light");
var curr = light.style.backgroundColor;
var next = colors.indexOf(curr)+1;
light.style.backgroundColor = colors[next%colors.length];
}
<h1>Disco Inferno</h1>
<div class="light" id="light" style="background-color:#00FFFF">
Burn, baby burn!
</div>
<button onClick="ColorFunction()">Burn!</button>

You could use an object for shifting the colors, after assigning directly a color to the div.
function ColorFunction() {
var colors = {
'rgb(0, 255, 255)': 'rgb(255, 255, 0)',
'rgb(255, 255, 0)': 'rgb(255, 0, 255)',
'rgb(255, 0, 255)': 'rgb(0, 255, 255)'
},
element = document.getElementById("light");
element.style.backgroundColor = colors[element.style.backgroundColor];
}
.main { width:250px; color: #202020; background-color: #d0d0d0; }
.light { width: 50px; height: 50px; background-color: #00ffff; }
#burn { width: 150px; font-style: italic; }
#button { font-style: bold; width: 150px; }
<div class="light" id="light" style="background-color: #00ffff;"></div>
<button onClick="ColorFunction()">Burn!</button>

There is no getItem() that is some made up method. Look at the console and you will see that it is an error. To read background color you should be using style.
var color = elementReference.style.backgroundColor
Now you are relying on a bad feature of JavaScript where you define a variable that matches an id of an element and it is magically a reference to that element.You should not do that. You should define the variable yourself.
var elementReference = document.getElementById("light");
Now the kicker, browsers returning different things when you read color values. SOme hex, some rgb. So checking for color is a bad thing to do. What to do? Use CSS classes.
function ColorFunction(){
var elem = document.getElementById("light");
if(elem.classList.contains("red")) {
elem.classList.remove("red");
elem.classList.add("blue");
} else if(elem.classList.contains("blue")) {
elem.classList.remove("blue");
elem.classList.add("green");
} else {
elem.classList.remove("green");
elem.classList.add("red");
}
}
.red { background-color: red;}
.blue {background-color: blue;}
.green {background-color: green;}
<h1>Disco Inferno</h1>
<div class="light red" id="light">
div
</div>
<button onClick="ColorFunction()">Burn!</button>
Now there are other ways to do the if check with add/remove, but that is the basic idea.

Related

How to change site colors and save in Local Storage?

How can I change site colors & save in localStorage?
I have a function in jQuery to allow users to the change background color of my website. The problem is, if they refresh the page background color automatically goes back to the default. How can I use localStorage with this jQuery function?
$(document).ready(function() {
/*-- Change color bg WPEAR.COM --*/
var resultPlaceholder = $('body');
var greenAndWhite = $('#green-and-white');
var redAndYellow = $('#red-and-yellow');
var blueAndPink = $('#blue-and-pink');
var yellowAndPink = $('#yellow-And-Pink');
greenAndWhite.click(function() {
resultPlaceholder.css({
'background': 'green'
});
});
redAndYellow.click(function() {
resultPlaceholder.css({
'background': 'red'
});
});
blueAndPink.click(function() {
resultPlaceholder.css({
'background': 'blue)'
});
});
yellowAndPink.click(function() {
resultPlaceholder.css({
'background': 'yellow'
});
});
})
/* -- change color wpear.com -- */
.button-wrapper {
position: fixed;
left: 0;
display: grid;
top: 40%;
margin: 0;
}
.change-color {
width: 40px;
height: 40px;
cursor: pointer;
border: none;
}
#red-and-yellow {
background: red;
}
#green-and-white {
background: green;
}
#blue-and-pink {
background: blue;
}
#yellow-And-Pink {
background: yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div class='button-wrapper'>
<button class='change-color' id='green-and-white' />
<button class='change-color' id='red-and-yellow' />
<button class='change-color' id='blue-and-pink' />
<button class='change-color' id='yellow-And-Pink' />
</div>
Write a function to save the selected theme to localStorage:
function saveTheme(color) {
localStorage.setItem('theme', color)
}
Save theme on every change:
greenAndWhite.click(function(){
resultPlaceholder.css({'background':'var(--linear-graBO)'});
saveTheme('var(--linear-graBO)')
});
// do this for each change
When page loads - check localStorage for saved theme [put in the <head> so it should run immediately]:
const savedTheme = localStorage.getItem('theme')
if (savedTheme) {
document.body.style.background = savedTheme
}
To do what you require simply set the localStorage value in the click handler. Then read it back out and set it when the page next loads:
Also note that your JS code can be DRY'd up by using the same event handler for all button elements and setting the background to match the clicked button.
jQuery($ => {
let $body = $('body');
let defaultBgColor = localStorage.getItem('body-bg-color');
defaultBgColor && $body.css('background-color', defaultBgColor);
$('.change-color').on('click', e => {
let bgColor = $(e.target).css('background-color');
$body.css('background-color', bgColor);
localStorage.setItem('body-bg-color', bgColor);
});
});
Finally, note the use of background-color, not background. The latter is a shortcut and using it to set the background color only may override other background-related styling.
Here's a working jsFiddle example, as SO snippets are sandboxed and don't allow access to localStorage.
Referring to your deleted question from today:
If you also want the text to change its color together with the background of the body, you can use the same jQuery css() method to manipulate the color property of the text:
$('#text').css('color', bgColor);
Working example:
i removed the localStorage stuff, for demonstration in the stack snippet
i added a white background for the text to see the effect
jQuery($ => {
let $body = $('body');
let defaultBgColor = 'white';
defaultBgColor && $body.css('background-color', defaultBgColor);
$('.change-color').on('click', e => {
let bgColor = $(e.target).css('background-color');
$body.css('background-color', bgColor);
$('#text').css('color', bgColor);
defaultBgColor = bgColor;
});
});
.button-wrapper {
position: fixed;
left: 0;
display: grid;
top: 40%;
margin: 0;
}
#text {
background-color: white;
}
.change-color {
width: 40px;
height: 40px;
cursor: pointer;
border: none;
}
#c1 {
background: red;
color: #fff;
}
#c2 {
background: green;
color: #000;
}
#c3 {
background: blue;
color: #fff;
}
#c4 {
background: yellow;
color: #000;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='button-wrapper'>
<button class='change-color' id='c1' />
<button class='change-color' id='c2' />
<button class='change-color' id='c3' />
<button class='change-color' id='c4' />
</div>
<div id='text'>
hello every body
</div>
If you also want to change the text colors you need to define the color combinations. That can be done for example with an if else chain, a switch case statement, an array or an object. But be aware, that the css() method only returns RGB colors...
definition in an object:
const color_combinations = {
'rgb(255, 0, 0)': 'yellow',
'rgb(0, 128, 0)': 'white',
'rgb(0, 0, 255)': 'orange',
'rgb(255, 255, 0)': 'black'
};
...
let bgColor = $(e.target).css('background-color');
$('#text').css('color', color_combinations[bgColor]);
Working example:
jQuery($ => {
let $body = $('body');
let defaultBgColor = 'white';
const color_combinations = {
'rgb(255, 0, 0)': 'yellow',
'rgb(0, 128, 0)': 'white',
'rgb(0, 0, 255)': 'orange',
'rgb(255, 255, 0)': 'black'
};
defaultBgColor && $body.css('background-color', defaultBgColor);
$('.change-color').on('click', e => {
let bgColor = $(e.target).css('background-color');
$body.css('background-color', bgColor);
$('#text').css('color', color_combinations[bgColor]);
defaultBgColor = bgColor;
});
});
.button-wrapper {
position: fixed;
left: 0;
display: grid;
top: 40%;
margin: 0;
}
.change-color {
width: 40px;
height: 40px;
cursor: pointer;
border: none;
}
#c1 {
background: red;
color: #fff;
}
#c2 {
background: green;
color: #000;
}
#c3 {
background: blue;
color: #fff;
}
#c4 {
background: yellow;
color: #000;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='button-wrapper'>
<button class='change-color' id='c1' />
<button class='change-color' id='c2' />
<button class='change-color' id='c3' />
<button class='change-color' id='c4' />
</div>
<div id='text'>
hello every body
</div>

i try to change all the black color codes into white color codes

I generated a TWBSColor code and i want to change all black color codes with white or other color at a certain time(i use a js code to look for the actual hour). i.e. if it's 12 PM all black codes change to white by searching the black codes and replace them with the white code color.
<script>var thehours = new Date().getHours();
if (thehours >= 8 && thehours < 20) {
document.body.style.backgroundColor = "white";
document.getElementById("liniasexy").background='linear-
gradient(to right, black, #f07f00)';
} else if (thehours >= 20 && thehours < 8) {
document.body.style.backgroundColor = "black";
}
</script>
i use this to change the background color.
A DOM Element object does not contain a property called background, you should set the value on the style property of that object, like so:
document.getElementById("liniasexy").style.background='linear-gradient(to right, black, #f07f00)';
You can add a class property to all elements you want to toggle background and use document.querySelectorAll('selectors') like this:
var toggleBackgroundItems = document.querySelectorAll(".toggle_bg");
toggleBackgroundItems.forEach(function(item) {
item.backgroundColor = 'white';
});
Working example:
function toggleBg() {
var toggleBackgroundItems = document.querySelectorAll(".toggle_bg");
toggleBackgroundItems.forEach(function(item) {
if(item.style.backgroundColor === 'black') {
item.style.backgroundColor = 'white';
item.style.color = 'black';
} else {
item.style.backgroundColor = 'black';
item.style.color = 'white';
}
});
}
#container {
display:flex
}
#container span {
width: 50px;
height: 50px;
text-align: center;
border: 1px solid #000;
}
.blue {
background-color: blue;
}
.green {
background-color: green;
}
<button onclick="toggleBg()">Toggle background color</button>
<br><br>
<p class="toggle_bg">A paragraph</p>
<div id="container">
<span class="blue">Blue</span>
<span class="toggle_bg">Toggle</span>
<span class="green">Green</span>
<span class="toggle_bg">Toggle</span>
<span class="toggle_bg">Toggle</span>
<span class="green">Green</span>
<span class="blue">Blue</span>
</div>

is there a way to reference a child node and get say an inherited background color?

I was doing some initial testing in jsFiddle as follows: https://jsfiddle.net/6pqxfy2o/
$(function(){
console.log("fired");
$("div").each(function(){
console.log($(this).attr("class"));
console.log($(this).css("background-color"))})
})
.color{
background-color:teal;
}
.dim{
width: 200px;
height: 200px;
}
.sub-dim{
width: 50px;
height:50px;
border: solid 1px white;
}
.ping {
background-color: cyan;
}
.ack {
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="dim color">
<div class="sub-dim ack">
</div>
<div class="sub-dim ping">
</div>
<div class="sub-dim">
</div>
</div>
This was showing that when running, it did not actually pass the inherited color into the child.
I am curious though how I can get the background color of the sub-dim which has no background color, such as: current background-color or nearest.
My end goal would be to say: When iterating over sub-dim to return [red, cyan,teal] or color codes. Based on the item I gave you, the div is transparent and the parent's color is showing through.
If the color is transparent, you can just set it to inherit and get the new computed color.
// Some browsers say "transparent" and some "rgba(0, 0, 0, 0)"
var transparent = (function() {
var backup = document.body.style.backgroundColor;
document.body.style.backgroundColor = 'transparent';
var bg = getComputedStyle(document.body).backgroundColor;
document.body.style.backgroundColor = backup;
return bg;
})();
[].forEach.call(document.getElementsByTagName("div"), function(el) {
var bg = getComputedStyle(el).backgroundColor;
if (bg === transparent) {
var backup = el.style.backgroundColor;
el.style.backgroundColor = 'inherit';
bg = getComputedStyle(el).backgroundColor;
el.style.backgroundColor = backup;
}
console.log(el.className, ":", bg);
});
.color {
background-color: teal;
}
.dim {
width: 200px;
height: 200px;
}
.sub-dim {
width: 50px;
height: 50px;
border: solid 1px white;
}
.ping {
background-color: cyan;
}
.ack {
background-color: red;
}
<div class="dim color">
<div class="sub-dim ack"></div>
<div class="sub-dim ping"></div>
<div class="sub-dim"></div>
</div>
I'm not sure I completely understand the problem, but you could try
.sub-dim.ack {
background-color: red;
}
or
.ack, .ack * {
background-color: red;
}
Obviosly try to be ore specific with which child elements you'd like to target.
This would likely be a lot easier in SASS.

Switch between black and white background

Aim: switch background color between black and white by clicking one button.
The following is my code, which does not work.
<html>
<body id="pageBody">
<style>
body {background: #000000; color: #FFFFFF;}
</style>
<p>A sentence.</p>
<button type="button" onclick="changeBG()">Change BG</button>
<script>
function changeBG() {
var bg = document.getElementById("pageBody");
if (bg.style.backgroundColor=="#000000") {
bg.style.backgroundColor="#FFFFFF";
bg.style.color="#000000";
}
else {
bg.style.backgroundColor="#000000";
bg.style.color="#FFFFFF";
}
}
</script>
</body>
</html>
You're comparing against a hex string - the browser will return RGB values
"rgb(0, 0, 0)" for black and "rgb(255, 255, 255)" for white.
This will work:
function changeBG() {
var bg = document.body;
if (bg.style.backgroundColor=="rgb(0, 0, 0)") {
bg.style.backgroundColor="#FFFFFF";
bg.style.color="#000000";
}
else {
bg.style.backgroundColor="#000000";
bg.style.color="#FFFFFF";
}
}
Working demo: http://jsfiddle.net/FTSYF/
Use classes to make the code more reusable, and to avoid dealing with browsers changing color mode:
body {background: #000; color: #fff;}
body.bg {background: #fff; color: #000;}
document.body.classList.toggle('bg');
If you want it to work on old browsers that don't support classList, then use (assuming body doesn't have other classes):
document.body.className = document.body.className ? 'bg' : '';

Windows Phone 8 HTML5 App and Themes

Iā€™m working on a WP8 HTML5 Game and was trying to be responsive to the theme the user selected.
I know I can use the Background tag in the CSS
body {
font-size: 11pt;
font-family: "Segoe WP";
letter-spacing: 0.02em;
background-color: Background;
color: #FFFFFF;
margin-
}
So now the background changes from Black to White but not the text color, obviously due to my having it set to #FFFFFF
I tried to change it in the javascript but oddly enough when I try document.body.style.backgroundcolor it returns ā€œā€ and even using a variable set by HEX or RGB returns false.
Anyone have a solution to this?
MainPage.xaml.cs
private void Browser_Loaded(object sender, RoutedEventArgs e)
{
Browser.IsScriptEnabled = true;
// Add your URL here
Browser.Navigate(new Uri(MainUri, UriKind.Relative));
Browser.Navigated += (o, s) => {
string theme = ((Visibility)Application.Current.Resources["PhoneLightThemeVisibility"] == Visibility.Visible) ?
"light" : "dark";
Browser.InvokeScript("eval", String.Format("document.body.className += ' {0}'", theme));
};
}
phone.css
body {
font-size: 11pt;
font-family: "Segoe WP";
letter-spacing: 0.02em;
background-color: Background;
margin-left: 24px;
}
.light {
color: #000000;
}
.dark {
color: #FFFFFF;
}
document.body.style.backgroundcolor is misspelled ...
Try: document.body.style.backgroundColor
With Uppercased C.
To change te color text of the body you can use document.body.style.color
EDIT:
By the way, probably there is a better way to solve your problem, if you are going to change a lot of css properties, you should create css classes, like this:
body {
/* default body css */
}
.myFirstColorSet {
background-color: #FFF;
color: #000;
...
}
.mySecondColorSet {
background-color: #000;
color: #FFF;
...
}
And then with javascript, just switch the body class
document.body.className = "mySecondColorSet";
Here is the fiddle with this example: http://jsfiddle.net/promatik/K75TG/
While the above XAML works so does this simply jQuery script
<script>
if ($("body").css("background-color") == 'rgb(0, 0, 0)'){
$("body").css("color","rgb(255, 255, 255)");
}
else{
$("body").css("color","rgb(0, 0, 0)");
}
</script>

Categories