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' : '';
Related
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>
I'm using this script to allow user to change the background color...
document.onclick = function SetFavColor(e) {
if (e.target.className == 'AvcGbtn') {
var favColor = e.target.style.backgroundColor;
localStorage.setItem('color', favColor);
document.body.style.backgroundColor = favColor;
console.log(favColor);
}
};
document.addEventListener('DOMContentLoaded', function GetFavColor() {
var favColor = document.body.style.backgroundColor;
var color = localStorage.getItem('color');
if (color === '') {
document.body.style.backgroundColor = favColor;
} else {
document.body.style.backgroundColor = color;
}
});
CSS:
body {
max-width: 100%;
min-width: 100%;
height: 100%;
font-family: normal;
font-style: normal;
font-weight: normal;
background-color: transparent;
}
.AvcGbtn {
display: inline-block;
width: 2em;
height: 2em;
}
HTML:
<span class="AvcGbtn" style="background: #ffffff; background-size: 100% 100%;" rel="nofollow"></span>
<span class="AvcGbtn" style="background: #757575; background-size: 100% 100%;" rel="nofollow"></span>
This is working, but the problem is that it shows the selected color after page is fully loaded. I want to show the color the user selects before the page is loaded.
Example: background color is white, and user selects red. The script shows a white background color before selection, and after the user selects red, the script changes the background color to red. How can I do this?
That is exactly what I'm trying to do with Javascript, example CSS
body:before {
background-color: red;
}
First you can simplify your logic of setting the color like below:
document.addEventListener('DOMContentLoaded', function GetFavColor() {
var color = localStorage.getItem('color');
if (color != '') {
document.body.style.backgroundColor = color;
}
});
You only need to change the color if there is something stored locally, if not the default color specified in the CSS will be used automatically.
In order to have a fast change you can get rid of any event and put your script within the head tag and instead of targeting the body element you can target the html one and you will have the same result due to background propagation:
<!DOCTYPE html>
<html>
<head>
<!-- coloration -->
<style>html {background:red} /*default color*/</style>
<script>
var color ="blue" /*localStorage.getItem('color')*/;
if (color != '') {
document.documentElement.style.backgroundColor = color;
}
</script>
<!-- -->
</head>
<body>
</body>
</html>
The snippet is changing the code, you need to test locally for more accurate results.
You need to use a different event onreadystatechange. This one fires before the onload. I played around a bit with the functions and set 'orange' as the default for this event and another as the click OFF the buttons as I disabled the cookie stuff that was not in your code. Note; if you want if as fast as the script can run it, do that. (red) as a call (green) as self executing.
I added a console.log so you could see that the colors do change from red to orange to blue based on events (happens fast, see the log times)
(window.getColor=function (c) {
var favColor = document.body.style.backgroundColor;
var color = !!c ? c : "#FFFAFF"; //getCookie('color');
if (color === '') {
document.body.style.backgroundColor = favColor;
} else {
document.body.style.backgroundColor = color;
}
console.log(color);
})('green');
function setColor(e) {
if (e.target.className == 'AvcGbtn') {
var favColor = e.target.style.backgroundColor;
//setCookie('color', favColor);
document.body.style.backgroundColor = favColor;
console.log(favColor);
} else {
getColor("#DAFFFA");
}
}
document.onreadystatechange = function() {
if (document.readyState === 'complete') {
//dom is ready, window.onload fires later
getColor("orange");
}
};
document.onclick = setColor;
window.onload = function() {
getColor('blue');
};
getColor('red');
body {
max-width: 100%;
min-width: 100%;
height: 100%;
font-family: normal;
font-style: normal;
font-weight: normal;
background-color: transparent;
}
.AvcGbtn {
display: inline-block;
width: 2em;
height: 2em;
}
<span class="AvcGbtn" style="background: #ffffff; background-size: 100% 100%;" rel="nofollow"></span>
<span class="AvcGbtn" style="background: #e8e8e8; background-size: 100% 100%;" rel="nofollow"></span>
Don't dismiss the awesome power of old-school Javascript: use document.write effectively in the right places, such as just at the end of the 'head' tag.
<head>
<link rel="stylesheet" type="text/css" href="..."/>
<script type="text/javascript">
(function(){
var color = localStorage.getItem('color');
if(typeof(color) === "string" && color != "") {
document.write("<style type=\"text\/css\">body{background-color:" + color + ";}</style>");
}
}());
</script>
</head>
Instead of putting your background-color-changing function on window.onload, try putting it in a <script> tag just after the opening <body> tag:
<html>
...
<body>
<script>
// This js code will be executed before the rest of the page is loaded
</script>
...
</body>
</html>
Since inline CSS is processed BEFORE javascript is processed, have you tried simply removing the background color from the inline CSS?
document.onclick = function(e) {
if (e.target.className == 'AvcGbtn') {
var favColor = e.target.style.backgroundColor;
setCookie('color', favColor);
document.body.style.backgroundColor = favColor;
console.log(favColor);
}
};
window.onload = function() {
var favColor = document.body.style.backgroundColor;
var color = getCookie('color');
if (color === '') {
document.body.style.backgroundColor = favColor;
} else {
document.body.style.backgroundColor = color;
}
};
body {
max-width: 100%;
min-width: 100%;
height: 100%;
font-family: normal;
font-style: normal;
font-weight: normal;
background-color: transparent;
}
<span class="AvcGbtn" style="background-size: 100% 100%;" rel="nofollow"></span>
<span class="AvcGbtn" style="background-size: 100% 100%;" rel="nofollow"></span>
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.
My problem is: I have three elements on a list, and I have to keep changing the text color when the mouse is hover.
So I am building 3 different functions, because the colors are different.
What I did is:
<script type="text/javascript">
var links = document.getElementsByClassName("menuitems");
function firsthover()
{
links[0].style.color = "rgb(204, 0, 0)"; /*this is for avoiding setInterval delay*/
setInterval(function(){
if(links[0].style.color == "rgb(204, 0, 0)")
{
links[0].style.color = "rgb(235, 153, 153)";
}
if(links[0].style.color == "rgb(235, 153, 153)")
{
links[0].style.color = "rgb(204, 0, 0)";
}
},1150);
}
</script>
The problem is: it changes the color just once.
I tried to use hexadecimal color too, just doesn't work.
Please be patient, I am still a novice.
The problem is a small logical flaw. The color does change, but it changes back right away.
If the first if statement evaluates as true and the color is set to rgb(235, 153, 153) the second if statement happens to be true as well, and gets checked right after the change. The color then changes back to the other rgb value.
Using else if instead of two separate statements fixes this. Alternatively you could place a return in the first if statement to prevent the second from being executed after the successful change.
if(links[0].style.color == "rgb(204, 0, 0)")
{
links[0].style.color = "rgb(235, 153, 153)";
}
else if(links[0].style.color == "rgb(235, 153, 153)")
{
links[0].style.color = "rgb(204, 0, 0)";
}
You can use CSS.
Put the code below inside your <head> tag.
<style type="text/css">
.menuitems {
color: rgb(204, 0, 0);
}
.menuitems:hover {
color: rgb(235, 153, 153);
}
</style>
It works perfectly well.
You can also use different colors for different items by using different classes.
Define a base class for menuitems, that will be the base color of them. Then add a different class for each color you would like to use.
Your CSS:
<style type="text/css">
.menuitems { /* base color */
color: rgb(204, 0, 0);
}
.menuitems:hover { /* base hover color */
color: rgb(235, 153, 153);
}
.menuitem-red:hover {
color: rgb(255, 0, 0) !important;
}
.menuitem-green:hover {
color: rgb(0, 255, 0) !important;
}
.menuitem-blue:hover {
color: rgb(0, 0, 255) !important;
}
</style>
Your HTML:
<ul id="menu">
<li class="menuitem">Menu item base</li>
<li class="menuitem menuitem-red">Menu item red</li>
<li class="menuitem menuitem-green">Menu item green</li>
<li class="menuitem menuitem-blue">Menu item blue</li>
</ul>
The name of classes I used and the colors are for sample purposes. Feel free to use the ones you think that fits better for your design.
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>