change background color with JavaScript - javascript

I have a main div containing n * n divs which have either a black background or a white one.
I want them to change their BGcolor by clicking on the main div.
Here's my code (that doesn't work obviously).
function invert(){
var divs = document.getsElementsByTagName("div");
for(i=0; i<divs.length; i++){
if(divs[i].style.backgroundColor=="black")
{
divs[i].style.backgroundColor="white";
}
else if (divs[i].style.backgroundColor=="white")
{
divs[i].style.backgroundColor="black";
}
}
}

If you haven't explicitly set a background color it may still be "" (at least that is what I see in Firefox) so none of your if condition matches.
Instead you could also switch to black if you detect that the current color is not set:
var color = divs[i].style.backgroundColor;
if (color === "black")
divs[i].style.backgroundColor = "white";
else if (!color || color === "white")
divs[i].style.backgroundColor = "black";

Give all the DIVs a default background color of white.
Add a black class to some of them.
Use classList.toggle to alternate the colors:
document.body.onclick= function() {
var divs= document.querySelectorAll('div');
for(var i = 0 ; i < divs.length ; i++) {
divs[i].classList.toggle('black');
}
}
body, html {
height: 100%;
background: lightyellow;
}
div {
width: 50px;
height: 50px;
border: 1px solid #333;
display: inline-block;
background: white;
}
.black {
background: black;
}
<div class="black"></div>
<div></div>
<div class="black"></div>
<div></div>
<div class="black"></div>
<div class="black"></div>
<div></div>
<div></div>

Two ways to achieve this:
1- style.backgroundColor (if you let the bg color info inline):
function turnthelights() {
var x = document.querySelectorAll(".inner");
var i;
for (i = 0; i < x.length; i++) {
if (x[i].style.backgroundColor === "black"){
x[i].style.backgroundColor = "white";
} else {
x[i].style.backgroundColor = "black";
}
}
}
body {
background-color: greenyellow;
}
.inner {
width: 80px;
height: 80px;
display: inline-block;
outline: 2px solid gold;
}
<div id=container onclick="turnthelights()">
<div class="inner" style="background-color: black"></div>
<div class="inner" style="background-color: white"></div>
<div class="inner" style="background-color: black"></div>
<div class="inner" style="background-color: white"></div>
<div class="inner" style="background-color: black"></div>
<div class="inner" style="background-color: white"></div>
</div>
2- getComputedStyle(element).backgroundColor (bg color info anywhere):
function turnthelights() {
var x = document.querySelectorAll(".inner");
var i;
for (i = 0; i < x.length; i++) {
var k = x[i];
var z = getComputedStyle(k).backgroundColor;
if (z == "rgb(0, 0, 0)"){
x[i].style.backgroundColor = "rgb(255, 255, 255)";
} else {
x[i].style.backgroundColor = "rgb(0, 0, 0)";
}
}
}
body {
background-color: hotpink;
}
.inner {
width: 80px;
height: 80px;
display: inline-block;
outline: 2px solid gold;
}
.black {
background-color: rgb(0, 0, 0);
}
.white {
background-color: rgb(255, 255, 255);
}
<div id=container onclick="turnthelights()">
<div class="inner black"></div>
<div class="inner white"></div>
<div class="inner black"></div>
<div class="inner white"></div>
<div class="inner black"></div>
<div class="inner white"></div>
</div>

Now 2020, and I find the real solution, get the style and set style must use a different method:
function changeColor(cell) {
var red = "rgba(255, 4, 10, 1)"; //rgba or rgb, so if you really want to use this, you need use regexp.
var grey = "rgba(230, 230, 230, 1)"; //pls change your css to this too.
var style = cell.computedStyleMap().get('background-color').toString();
if (style == grey) {
cell.style.backgroundColor = red;
} else if (style == red) {
cell.style.backgroundColor = grey;
}
}
for chrome this is ok, but, maybe other browser with other color format, you need test it.

Related

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.

Javascript - Change colour of div based on current colour

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.

getting a div to flash for 1 second using setTimeout

im trying to get a set of four different colored div's to flash for a second in a random sequence that keeps repeating adding one more flash each time, by adding a class that sets their opacity to 0, but only the last div in the sequence appears to be flashing, here is the javascript code:
$(function() {
x="";
for(i=0;i<3;i++){
x+=String(Math.floor(Math.random()*4)+1);
$("#test").append(x);
j=0;
flashinglight();
$("#red").removeClass("redflash");
$("#blue").removeClass("blueflash");
$("#yellow").removeClass("yellowflash");
$("#green").removeClass("greenflash");
};
})
function flashinglight(){
if(j<x.length){
setTimeout(function(){
$("#red").removeClass("redflash");
$("#yellow").removeClass("yellowflash");
$("#green").removeClass("greenflash");
$("#blue").removeClass("blueflash");
if(x[j]=="1"){
$("#red").addClass("redflash");
}
else if(x[j]=="2"){
$("#yellow").addClass("yellowflash");
}
else if(x[j]=="3"){
$("#green").addClass("greenflash");
}
else if(x[j]=="4"){
$("#blue").addClass("blueflash");
}
j+=1;
flashinglight();
},1000);
}
else{
return;
}
}
You'll be glad to know it can ba a lot simpler than that. :-) See comments inline:
// Your existing ready callback
$(function() {
// Array of color names
var colors = ["red", "blue", "yellow", "green"];
// Start
flashlight();
function flashlight() {
// Get a random color
var c = colors[Math.floor(Math.random() * colors.length)];
// Get the matching element
var elm = $("#" + c);
// And class
var cls = c + "flash";
// Add the class
elm.addClass(cls);
// A second later...
setTimeout(function() {
// Remove it
elm.removeClass(cls);
// And run again
flashlight();
}, 1000);
}
});
.container div {
display: inline-block;
width: 40px;
height: 40px;
}
#red {
border: 2px solid red;
}
#blue {
border: 2px solid blue;
}
#yellow {
border: 2px solid yellow;
}
#green {
border: 2px solid green;
}
.redflash {
background-color: red;
}
.blueflash {
background-color: blue;
}
.yellowflash {
background-color: yellow;
}
.greenflash {
background-color: green;
}
<div class="container">
<div id="red"></div>
<div id="blue"></div>
<div id="yellow"></div>
<div id="green"></div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
That "flashes" for a full second before moving on to the next. If you need a shorter flash and a delay between them, it's just a matter of setting up a second timer.
Watching that for a moment, it bothered me when the same color was picked twice. So if you want a version that excludes the current color when picking the next:
// Your existing ready callback
$(function() {
// Array of color names
var colors = ["red", "blue", "yellow", "green"];
// The current color
var color = null;
// Start
flashlight();
function flashlight() {
// Pick a random color, excluding the one we're currently using
var available = colors.filter(function(c) {
return c !== color;
});
color = available[Math.floor(Math.random() * available.length)];
// Get the matching element
var elm = $("#" + color);
// And class
var cls = color + "flash";
// Add the class
elm.addClass(cls);
// A second later...
setTimeout(function() {
// Remove it
elm.removeClass(cls);
// And run again
flashlight();
}, 1000);
}
});
.container div {
display: inline-block;
width: 40px;
height: 40px;
}
#red {
border: 2px solid red;
}
#blue {
border: 2px solid blue;
}
#yellow {
border: 2px solid yellow;
}
#green {
border: 2px solid green;
}
.redflash {
background-color: red;
}
.blueflash {
background-color: blue;
}
.yellowflash {
background-color: yellow;
}
.greenflash {
background-color: green;
}
<div class="container">
<div id="red"></div>
<div id="blue"></div>
<div id="yellow"></div>
<div id="green"></div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>

Change background color of a div on hover from an array of colors

I am new to jQuery and I am experimenting a bit here. Please be patient.
I am trying to give div's a "random" background color on hover. If the div is not hovered I want them to be white.
I realize that random may not be the right word here because I want the script to chose a color from the following array, preferably in the same order: ['#009c61', '#cc0099', '#cc9900', '#cc0033', '#0099cc', '#6600cc', '#66cc00']
I guess some of the problem is because all divs have the same class.
How can this be achieved with jQuery?
jQuery(document).ready(function($) {
var bgColorArray = ['#009c61', '#cc0099', '#cc9900', '#cc0033', '#0099cc', '#6600cc', '#66cc00'],
selectBG = bgColorArray[Math.floor(Math.random() * bgColorArray.length)];
$('.article-container').css('background-color', selectBG)
});
.article-container {
color: #000;
font-family: 'Oswald', sans-serif;
text-align: center;
height: 200px;
width: 200px;
border: solid 3px #000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="article-container">Div 1</div>
<div class="article-container">Div 2</div>
<div class="article-container">Div 3</div>
<div class="article-container">Div 4</div>
So far I have tried this:
jQuery(document).ready(function($) {
var bgColorArray = ['#009c61', '#cc0099', '#cc9900', '#cc0033', '#0099cc', '#6600cc', '#66cc00'],
selectBG = bgColorArray[Math.floor(Math.random() * bgColorArray.length)];
$('.article-container').css('background-color', selectBG)
});
Problem is this changes the color on page refresh and it changes the bg color of all divs.
Try to use .hover(mouseInHandler,mouseOutHandler) function at this context,
var colors = ['#009c61', '#cc0099', '#cc9900', '#cc0033', '#0099cc', '#6600cc', '#66cc00'];
$(".article-container").hover(function() {
$(this).css("background-color", colors[(Math.random() * colors.length) | 0])
}, function() {
$(this).css("background-color", "")
});
DEMO
Take a look at this
Jquery :
$(document).ready(function()
{
$("a").hover(function(e)
{
var randomClass = getRandomClass();
$(e.target).attr("class", randomClass);
});
});
function getRandomClass()
{
//Store available css classes
var classes = new Array("green", "purple", "teal", "violet", "pink");
//Give a random number from 0 to 5
var randomNumber = Math.floor(Math.random()*6);
return classes[randomNumber];
}
CSS :
a.green:hover { color: #1ace84; }
a.purple:hover { color: #a262c0; }
a.teal:hover { color: #4ac0aa; }
a.violet:hover { color: #8c78ba; }
a.pink:hover { color: #d529cd; }
Searched on google and got it from Telmo
Cool idea. I just wanted to take a stab at making something pretty.
var numberOfBlocks= 250;
var colors = ['#009c61','#cc0099','#cc9900','#cc0033','#0099cc','#6600cc','#66cc00'];
var lastColor = 0;
(function init() {
var wrap = document.getElementById('wrap');
var block = document.createElement('div');
block.setAttribute('class', 'block');
for(var i=0; i<numberOfBlocks; i++) {
wrap.appendChild(block.cloneNode(true));
}
$('.block').hover(function() {
$(this).css('background-color', colors[lastColor++])
lastColor = (lastColor>=colors.length?0:lastColor);
},
function() {
$(this).css('background-color', '#fff');
});
})();
.block {
width: 20px;
height: 20px;
border: 1px solid white;
display: inline-block;
margin-top: -5px;
margin-left: -1px;
transition: all .1s ease-in-out;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="wrap">
</div>

Categories