I have 3 div's
<div id="box1"></div>
<div id="box2"></div>
<div id="box3"></div>
<button>Enter</button>
I want to give it a random color using javascript controlled css.
Like this:
var randomColor = Math.ceil(Math.random() * 3);
var color = "";
//Accessing the divs
var box1 = document.querySelector("#box1");
var box2 = document.querySelector("#box2");
var box3 = document.querySelector("#box3");
//Event
var button = document.querySelector("button");
button.addEventListener("click", randomize, false);
button.style.cursor = "pointer";
function render(){
box1.style.background = color;
box2.style.background = color;
box3.style.background = color;
}
function randomize(randomColor){
switch(randomColor){
case 1:
color = "red";
break;
case 2:
color = "blue";
break;
case 3:
color = "green";
break;
}
render();
}
The problem is that, it's giving me the same color in every div.
Any idea how can i solve this, I want to do it pure javascript and css no jquery if possible. Im still learning javascript. Thank you..
You could use classes instead of ids and simplify your code to following.
// You could easily add more colors to this array.
var colors = ['red', 'blue', 'green', 'teal', 'rosybrown', 'tan', 'plum', 'saddlebrown'];
var boxes = document.querySelectorAll(".box");
var button = document.querySelector("button");
button.addEventListener("click", function () {
for (i = 0; i < boxes.length; i++) {
// Pick a random color from the array 'colors'.
boxes[i].style.backgroundColor = colors[Math.floor(Math.random() * colors.length)];
boxes[i].style.width = '100px';
boxes[i].style.height = '100px';
boxes[i].style.display = 'inline-block';
}
});
button.style.cursor = "pointer";
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<button>Enter</button>
Randomizing the colors on page refresh/load.
// You could easily add more colors to this array.
var colors = ['red', 'blue', 'green', 'teal', 'rosybrown', 'tan', 'plum', 'saddlebrown'];
var boxes = document.querySelectorAll(".box");
for (i = 0; i < boxes.length; i++) {
// Pick a random color from the array 'colors'.
boxes[i].style.backgroundColor = colors[Math.floor(Math.random() * colors.length)];
boxes[i].style.width = '100px';
boxes[i].style.height = '100px';
boxes[i].style.display = 'inline-block';
}
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
How about this?
http://jsfiddle.net/stackmanoz/vymmb10s/
CSS-
div[class^="box"]{
width:100px;
height:100px;
border:1px solid;
display:inline-block;
}
jQuery-
var colors = ['red', 'blue', 'green', 'gray', 'black', 'yellow'];
$(function(){
$("#btn").click(function() {
$('div[class^="box"]').each(function(){
var randomColor = Math.floor(Math.random() * colors.length)
$(this).css('background-color', colors[randomColor])
});
});
});
var r = Math.floor(Math.random()*255);
var g = Math.floor(Math.random()*255);
var b = Math.floor(Math.random()*255);
for (var i = 0; i <= 5; i++) {
var div = document.getElementsByClassName("div")[i].style.backgroundColor = "rgb("+r+","+g+","+b+")";
}
div {
width: 200px;
height:200px;
display: inline;
float: left;
margin: 15px;
background-color: red;
}
<div class="div"></div>
<div class="div"></div>
<div class="div"></div>
<div class="div"></div>
<div class="div"></div>
<div class="div"></div>
*
<html>
<head>
<style>
div {
width: 100px;
height: 100px;
position: relative;
border: 1px solid black;
float: left;
margin: 5px;
}
</style>
</head>
<body>
<div id="first"></div>
<div id="second"></div>
<div id="third"></div>
<div id="fourth"></div>
</body>
<script>
let colors = ['red', 'green', 'blue', 'yellow'];
(function () {
document.getElementById("first").style.backgroundColor = assignColor();
document.getElementById("second").style.backgroundColor = assignColor();
document.getElementById("third").style.backgroundColor = assignColor();
document.getElementById("fourth").style.backgroundColor = assignColor();
})();
function assignColor() {
let colorIndex = Math.floor(Math.random() * colors.length);
let color = colors[colorIndex];
colors.splice(colorIndex, 1);
return color;
}
</script>
</html>
I was appalled by the list of named string colors and didn't see anyone using hex. For anyone like me that wanted something different, here you go:
function randomInt(max=1, min=0){
// scale random number from 0 to 1 to desired min and max
return parseInt( Math.random() * (max - min) + min );
}
function twoPlaces(sNum=''){
// make sure all strings have a length greater than 1
// eg: "f" => "0f"
return sNum.length > 1 ? sNum : twoPlaces('0'+sNum);
}
function randomColor(){
// make each color's hex string
let r = twoPlaces( randomInt(255,0).toString(16) );
let g = twoPlaces( randomInt(255,0).toString(16) );
let b = twoPlaces( randomInt(255,0).toString(16) );
// return hex color string
return `#${r}${g}${b}`;
}
function updateColors(){
// loop through all elements with class "random"
document.querySelectorAll(".random").forEach( (el)=>{
// set each element/'s color to a random hex
el.setAttribute("style",`background-color:${ randomColor() }`);
} );
}
// add function to randomizer
let randomizer = document.querySelector("#colorRandomizer");
randomizer.addEventListener("click",updateColors);
// initialize colors
randomizer.dispatchEvent( new Event("click") );
div {
width: 100%;
height: 100%;
display: grid;
grid-template-columns: repeat(auto-fit, minmax(100px, 1fr));
}
.random{
height: 100px;
}
<button id="colorRandomizer">Randomize</button>
<div>
<div class="random"></div>
<div class="random"></div>
<div class="random"></div>
<div class="random"></div>
<div class="random"></div>
<div class="random"></div>
</div>
Related
I'm making a color guessing game in JS. You're given the RGB value of a color, and you're supposed to click one of the three divs with that specific color while the other two have a different color. I've managed to make these three divs have three different random colors; however, I can't figure out how to make one of them have the winning color.
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="style.css">
<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>Document</title>
</head>
<body>
<h1 class="text-centered">Guess The Color!</h1>
<h2 class="text-centered" id="colorguess"></h2>
<div class="box-container">
<div class="box">
</div>
<div class="box">
</div>
<div class="box">
</div>
</div>
</body>
<script src="script.js"></script>
</html>
*{
box-sizing: border-box;
}
body{
font-family: arial;
background-color: #1c1874;
color: rgb(105, 105, 139);
color: #fff;
}
.text-centered{
text-align: center;
text-shadow: 0px 2px 2px rgba(150, 150, 150, 1);
}
.box-container{
padding: 200px;
align-self: center;
display: flex;
flex-direction: row;
justify-content:space-evenly;
}
.box{
width: 200px;
height: 200px;
border-radius: 20px;
cursor: pointer;
}
function gamestart(){
var r = Math.floor(Math.random() * 256);
var g = Math.floor(Math.random() * 256);
var b = Math.floor(Math.random() * 256);
var rgb = document.getElementById('colorguess');
//here i defined the initial winning color
rgbvaluetrue = "rgb("+r+", "+g+", "+b+")";
rgb.innerHTML = rgbvaluetrue;
var body = document.getElementsByTagName('body');
var box = document.getElementsByClassName('box');
for(var i=0;i<=box.length;i++){
var r,g,b = Math.floor(Math.random() * 256);
rgbvalue = "rgb("+r+", "+g+", "+b+")";
box[i].style.backgroundColor = rgbvalue;
}
//here I am trying to assign the initial rgb value to one of the divs randomly
var rand = Math.floor(Math.random() * 3);
//here I check if the div you clicked on is correct
box[rand].style.backgroundColor = rgbvaluetrue;
for(var i=0;i<=box.length;i++){
box[i].addEventListener("click", function(el) {
if (el.style.backgroundColor == rgbvaluetrue){
h1 = document.getElementsByTagName('h1');
h1.innerHTML = "BRAVO";
}
else{
gamestart();
}
})
}
}
gamestart();
The code for the game is there but there were three of mistakes in it.
I'll go through them one by one:
The two for cycles are run 4 times instead of 3. The termination condition i<=box.length should be replaced by i<box.length.
The addEventListener handler doesn't get the element as an input parameter but the event itself. You can then get the element with the target property like this: event.target.
After this assignment h1 = document.getElementsByTagName('h1'); h1 contains an array with all the h1 elements so you can't assign use h1.innerHTML = "BRAVO"; to assign a content to it. I changed it to display the success text in the same h1 you are using to show the rgb value like this:
h1 = document.getElementById('colorguess');
Lastly, in your code the addEventListener is called every time the game is played.
After the first victory you will have 2 listeners for every box making the game unplayable unless you refresh the entire page. To solve this I moved the listeners registration in a init function that you have to call only once at the start of the first game. (Another way was to remove and then readd the event listener every time)
Here is the complete js code. I didn't touch the html/css parts.
var rgbvaluetrue;
function initGame() {
var box = document.getElementsByClassName('box');
for(var i=0;i<box.length;i++){
box[i].addEventListener("click", checkWinner);
}
}
function gamestart(){
var r = Math.floor(Math.random() * 256);
var g = Math.floor(Math.random() * 256);
var b = Math.floor(Math.random() * 256);
var rgb = document.getElementById('colorguess');
//here i defined the initial winning color
rgbvaluetrue = "rgb("+r+", "+g+", "+b+")";
rgb.innerHTML = rgbvaluetrue;
var body = document.getElementsByTagName('body');
var box = document.getElementsByClassName('box');
for(var i=0;i<box.length;i++){
var r,g,b = Math.floor(Math.random() * 256);
rgbvalue = "rgb("+r+", "+g+", "+b+")";
box[i].style.backgroundColor = rgbvalue;
}
//here I am trying to assign the initial rgb value to one of the divs randomly
var rand = Math.floor(Math.random() * 3);
//here I check if the div you clicked on is correct
box[rand].style.backgroundColor = rgbvaluetrue;
}
function checkWinner(event) {
if (event.target.style.backgroundColor === rgbvaluetrue){
h1 = document.getElementById('colorguess');
h1.innerHTML = "BRAVO";
}
else{
gamestart();
}
}
initGame();
gamestart();
There is a small mistake in the loops:
for(var i=0;i<=box.length;i++){ It goes 4 times, but you have 3 boxes
change to for(var i=0;i<box.length;i++){
There are multiple issues:
for loops are iterating more times than needed
var r, g, b = ... will only assign b. r and g will remain undefined
I refactored the JavaScript and fixed all issues, run the below snippet:
const getRandomColor = () => {
return `rgb(${Math.floor(Math.random() * 256)}, ${Math.floor(Math.random() * 256)}, ${Math.floor(Math.random() * 256)})`;
}
let colorToGuess = '';
const resultContainer = document.querySelector('#result');
const colorToGuessContainer = document.querySelector('#color-to-guess');
const boxes = document.querySelectorAll('.box-container .box');
const startGame = () => {
resultContainer.innerText = "Guess The Color!"
colorToGuess = getRandomColor();
colorToGuessContainer.innerHTML = colorToGuess;
const randomBoxIndex = Math.floor(Math.random() * boxes.length);
boxes.forEach((box, index) => {
box.style.backgroundColor = index === randomBoxIndex ? colorToGuess : getRandomColor();
})
}
boxes.forEach((box) => {
box.addEventListener('click', ({
target
}) => {
if (target.style.backgroundColor === colorToGuess) {
resultContainer.innerText = "You guessed it, click me to play again."
} else {
startGame()
}
})
})
startGame();
resultContainer.addEventListener('click', startGame)
* {
box-sizing: border-box;
}
body {
font-family: arial;
background-color: #1c1874;
color: white;
}
.text-centered {
text-align: center;
text-shadow: 0px 2px 2px rgba(150, 150, 150, 1);
}
.box-container {
padding: 2rem;
display: flex;
align-items: center;
justify-content: center;
}
.box {
width: 200px;
height: 200px;
border-radius: 20px;
cursor: pointer;
}
<h1 class="text-centered" id="result"></h1>
<h2 class="text-centered" id="color-to-guess"></h2>
<div class="box-container">
<div class="box">
</div>
<div class="box">
</div>
<div class="box">
</div>
</div>
How do you change the colors of the 3 divs using the 3 arrays provided when i click the change theme button.
<script>
var colors = ['red', 'green', 'blue']
var colors1 = ['teal', 'brown', 'tan']
var colors2 = ['orange', 'purple', 'black'];
var boxed = document.querySelectorAll(".box");
var button = document.querySelector("button");
button.addEventListener("click", function () {
for (i = 0; i < boxed.length; i++) {
boxed[i].style.backgroundColor = colors[Math.floor(Math.random() * 3)];
boxed[i].style.width = '100px';
boxed[i].style.height = '100px';
boxed[i].style.display = 'inline-block';
}
});
button.style.cursor = "pointer";
</script>
I think you want something like this-
Updated code for the requirement
var colors = [
['red', 'green', 'blue'],
['teal', 'brown', 'tan'],
['orange', 'purple', 'black']
]
var boxed = document.querySelectorAll(".box");
var button = document.querySelector("button");
button.addEventListener("click", function () {
let colorIndex = Math.floor(Math.random() * 3);
for (i = 0; i < boxed.length; i++) {
boxed[i].style.backgroundColor = colors[colorIndex][i];
boxed[i].style.width = '100px';
boxed[i].style.height = '100px';
boxed[i].style.display = 'inline-block';
}
});
button.style.cursor = "pointer";
.box {
width: 100px;
height: 100px;
display: inline-block;
background: gray;
}
<div class="box">1</div>
<div class="box">2</div>
<div class="box">3</div>
<button>Theme</button>
something like that ?
const colors= [ ['red', 'green', 'blue']
, ['teal', 'brown', 'tan']
, ['orange', 'purple', 'black'] ]
, boxed = document.querySelectorAll(".box")
, button = document.querySelector("button")
;
button.onclick=_=>
{
let colorN = Math.floor(Math.random() *3)
boxed.forEach((box,i)=>
{
box.style.backgroundColor = colors[colorN][i];
})
}
.box {
display: inline-block;
width: 100px;
height: 100px;
background-color: lightgrey;
}
<div class="box">box 1</div>
<div class="box">box 2</div>
<div class="box">box 3</div>
<button>change Colors</button>
Hello there i'm doing an course about JavaScript in the first exercise they ask to make a button that creates boxes,and in the second exercise they ask to use an function to when the mouse hover over the boxes they change color randomly, but i didn't manged to do it so here's firstly the box maker:
<body>
<button>CREATE</button>
<p>BOXES GENERATOR</p>
<div class="container"></div>
</body>
var button1 = document.querySelector("button");
button1.onclick = function() {
var cubeElement = document.createElement("div");
cubeElement.setAttribute("class", "bt");
var bodyElement = document.querySelector(".container");
bodyElement.appendChild(cubeElement);
var cubestyleElement = document.querySelectorAll(".bt");
for (var i = 0; i < cubestyleElement.length; i++) {
cubestyleElement[i].setAttribute(
"style",
"background: #850900; height: 100px; width: 100px; border: solid #000 2px;"
);
}
};
and there's the function to make it change colors randomly:
function getRandomColor() {
var letters = "0123456789ABCDEF";
var color = "#";
for (var i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
};
var newColor = getRandomColor(); // #E943F0
Here you go:
function getRandomColor() {
var letters = "0123456789ABCDEF";
var color = "#";
for (var i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
};
var i = 0;
var button1 = document.querySelector("button");
button1.onclick = function() {
var cubeElement = document.createElement("div");
cubeElement.setAttribute("class", "bt");
var bodyElement = document.querySelector(".container");
bodyElement.appendChild(cubeElement);
var cubestyleElement = document.querySelectorAll(".bt");
for (i; i < cubestyleElement.length; i++) {
var element = cubestyleElement[i];
element.setAttribute(
"style",
"background: #850900; height: 100px; width: 100px; border: solid #000 2px;"
);
element.onmouseover = function(){
var newColor = getRandomColor();
element.setAttribute(
"style",
"background:"+ newColor+"; height: 100px; width: 100px; border: solid #000 2px;"
);
}
}
};
<button>CREATE</button>
<p>BOXES GENERATOR</p>
<div class="container"></div>
Please check this.. Are you looking this?
var button1 = document.querySelector("button");
button1.onclick = function() {
var cubeElement = document.createElement("div");
cubeElement.setAttribute("class", "bt");
cubeElement.addEventListener('mouseover', function(event) {
event.target.style.backgroundColor = getRandomColor();
});
var bodyElement = document.querySelector(".container");
bodyElement.appendChild(cubeElement);
var cubestyleElement = document.querySelectorAll(".bt");
for (var i = 0; i < cubestyleElement.length; i++) {
cubestyleElement[i].setAttribute(
"style",
"background: #850900; height: 100px; width: 100px; border: solid #000 2px;"
);
}
};
function getRandomColor() {
var letters = "0123456789ABCDEF";
var color = "#";
for (var i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
};
<body>
<button>CREATE</button>
<p>BOXES GENERATOR</p>
<div class="container"></div>
</body>
Please let me know if you have any query.
I want to obtain different height values for each div in both the 'CardContainer' and 'Two' divs. I would like to randomize those values upon each click event without repeating any of the values in the array.
http://codepen.io/jlhanna/pen/oBjrov
HTML
<html>
<button id="press" type="Button" value="Shake">Test</button>
<div id="cardContainer"></div>
<div id="two"></div>
<div id="three"></div>
</html>
CSS
#cardContainer div {border:solid 1px black; width: 20px;}
#two {border:solid 1px black; width: 20px; position: absolute; top: 20px; left: 50px;}
button {display: block;}
JS
var balls90 = ['1px', '5px', '10px', '20px', '40px', '80px', '160px', '320px'];
var cardContainer= document.getElementById("cardContainer");
var two= document.getElementById("two");
var $all = $("#cardContainer").push(balls90);
var $next = $("#two").push(balls90);
function getNumbers() {
var player1 = new Array();
balls90.sort(function() {
return [Math.floor(Math.random() * balls90.length)];
});
$("#press").click(function() {
$("#cardContainer").empty();
});
document.getElementById("press").addEventListener('click',getNumbers,true);
for (var i = 1; i <= 4; i++) {
var div = document.createElement("div");
div.style.height = (balls90[i]);
cardContainer.appendChild(div);
}
}
getNumbers();
function getMore() {
var player1 = new Array();
balls90.sort(function() {
return [Math.floor(Math.random() * balls90.length)];
});
$("#press").click(function() {
$("#two").empty();
});
document.getElementById("press").addEventListener('click',getMore,true);
for (var i = 1; i <= 4; i++) {
var div = document.createElement("div");
div.style.height = (balls90[i]);
div.style.border = "thin solid black";
two.appendChild(div);
}
}
getMore();
would this work?
var balls90 = ['1px', '5px', '10px', '20px', '40px', '80px', '160px', '320px'];
var randomBalls90 = [];
var $cardContainer = $("#cardContainer");
var $two = $("#two");
$("#press").click(function() {
$("#cardContainer, #two").empty();
getNumbers();
});
function makedivs (el) {
for (var i = 1; i <= 4; i++) {
var $div = $("<div>");
$div.css({
height: randomBalls90[0],
border: "1px solid red"
});
$(el).append($div);
randomBalls90.splice(0, 1);
}
}
function getNumbers() {
balls90.sort(function() {
return [Math.floor(Math.random() * balls90.length)];
});
randomBalls90 = JSON.parse(JSON.stringify(balls90));
makedivs($cardContainer);
makedivs($two);
}
getNumbers();
Basically, I made making the random divs as a seperate function that accepts a element to append to.
When getNumbers is run, it clones the balls90 Array JSON.parse(JSON.stringify()) then loops through the array and on each loop, you remove the first object of the array so it's never repeated.
I want to create an event where the DIVs are clicked and they change to a random color. I'm fairly confident that this is the general setup, but I'm just overlooking some small error(s)...
HTML
<style>
.square {
width: 100px;
height: 100px;
background-color: #000000;
margin: 5px;
}
</style>
<div id="container">
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
</div>
JAVASCRIPT
var squareRef = document.getElementById("container");
for(var i = 0; i < squareRef.length; i++) {
squareRef[i].addEventListener("click", changeColor);
}
function changeColor(event) {
event.target.style.backgroundColor = "randomColor()";
}
function randomColor() {
var randomRed = Math.floor(Math.random() * 255);
var randomGreen = Math.floor(Math.random() * 255);
var randomBlue = Math.floor(Math.random() * 255);
//create the string that is the ‘random color’
var randomColor = "rgb("+randomRed+","+randomGreen+","+randomBlue+")";
return randomColor;
}
Here is a fiddle: http://jsfiddle.net/r2vfa2s4/
Two things.
Change the first line to:
var squareRef = document.getElementsByClassName("square");
Remove quotes when you invoke randomColor(). I.e.:
event.target.style.backgroundColor = randomColor();
You Made Mistakes on Two Lines
You Have to change color of particular div not the container div so please change this
var squareRef = document.getElementById("container");
To
var squareRef = document.getElementsByClassName("square");
AND
You are calling function in a wrong way:
Change this line
event.target.style.backgroundColor = "randomColor()";
To
event.target.style.backgroundColor = randomColor();
Try This
var squareRef = document.getElementsByClassName("square");
for(var i = 0; i < squareRef.length; i++) {
squareRef[i].addEventListener("click", changeColor);
}
function changeColor(event) {
event.target.style.backgroundColor = randomColor();
}
function randomColor() {
var randomRed = Math.floor(Math.random() * 255);
var randomGreen = Math.floor(Math.random() * 255);
var randomBlue = Math.floor(Math.random() * 255);
//create the string that is the ‘random color’
var randomColor = "rgb("+randomRed+","+randomGreen+","+randomBlue+")";
return randomColor;
}
.square {
width: 100px;
height: 100px;
background-color: #000000;
margin: 5px;
}
<div id="container">
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
</div>
For the JavaScript, this works:
var ref = [].slice.call(document.getElementsByClassName("square"));
ref.forEach(function(v,k,a)
{
v.onclick = function()
{
var clr = Math.floor(Math.random() * 255);
this.style.backgroundColor = 'hsla('+clr+',100%,50%,1)';
};
});
By the way:
looping through a nodeList got from "getElementsByClassName", produces an error when trying to reference, as a nodeList contains non-elements as well.
The [].slice.call part takes care of that ;)