Stuck on unexpected container childnodes - javascript HTML - javascript

Can anyone help me on Javascript coding? Lines13-14 i try to create 9x div(class="square") but i get 18 childnodes when i check container from console. It also prints 18 in total?
Second issue is about resetbutton. When i try to clear container childnodes to start a new game it gives error. (maybe there's no need to add some code to clear container?) Thank you.
// Create div elements inside container according to difficulty
for (let i = 0; i < difficulty; i++) {
container.appendChild(createDiv());
}
function createDiv() {
// create a div element and assign "square" class
let div = document.createElement("div");
div.classList.toggle("square");
return div;
};
function resetGame () {
// Clean boxes
for (let i = 0; i < difficulty; i++) {
container.removeChild(container.childNodes[i]);
}
var buttonReset = document.querySelector("#reset");
var container = document.querySelector("#boxes");
var difficulty = 9;
var h1 = document.querySelectorAll("h1");
var message = document.querySelector("#message");
var pickedColor = "";
// Listener for reset button
buttonReset.addEventListener("click", resetGame());
function newGame () {
// Create div elements inside container according to difficulty
for (let i = 0; i < difficulty; i++) {
container.appendChild(createDiv());
}
// Select all squares.
var squares = document.querySelectorAll(".square");
// Create and fill colors array
let colors = createColors();
// Pick a random color from colors
pickedColor = colors[
Math.floor(Math.random() * squares.length)
];
// Update text on screen
colorDisplay.textContent = pickedColor;
// Draw squares with colors and check clicked color.
for(let i = 0; i < squares.length; i++) {
// Add initial colors to squares
squares[i].style.backgroundColor = colors[i];
// Add click events to squares
squares[i].addEventListener("click", function() {
// check if clickedColor is pickedColor.
if (this.style.backgroundColor === pickedColor) {
message.textContent = "Yes, you've found the color";
//change all square colors to pickedColor
for (let i = 0; i < difficulty; i++) {
// Add initial colors to squares
squares[i].style.backgroundColor = pickedColor;
};
h1.forEach(function(item) {
item.style.backgroundColor = pickedColor;
});
} else {
message.textContent = "Please try again!"
this.style.backgroundColor = "#232323";
}
});
};
}
function createColors() {
let createdList = [];
for(let i = 0; i < difficulty; i++) {
createdList.push("rgb(" +
Math.floor(Math.random() * 256) + ", " +
Math.floor(Math.random() * 256) + ", " +
Math.floor(Math.random() * 256) + ")");
};
return createdList;
};
function createDiv() {
// create a div element and assign "square" class
let div = document.createElement("div");
div.classList.toggle("square");
return div;
};
function resetGame () {
/// Clean boxes
for (let i = 0; i < difficulty; i++) {
container.removeChild(container.childNodes[i]);
}
// Create new game
newGame();
};
newGame(); // Only for first run
body {
background-color: #232323;
}
h1 {
color: white;
}
.square {
background: greenyellow;
float: left;
margin: 1.66%;
padding-bottom: 30%;
width: 30%;
}
#container {
margin: 0 auto;
max-width: 800px;
}
#stripe {
background: white;
color: black;
height: 30px;
text-align: center;
}
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<title>Color Game</title>
</head>
<body>
<h1 class="display-4">THE GREAT</h1>
<h1 class="display-2"><span id="colorDisplay">RGB(175, 203, 2)</span></h1>
<h1 class="display-4">GUESSING GAME</h1>
<div id="stripe">
<button id="reset">NEW COLORS</button>
<span id="message"></span>
</div>
<!-- Color boxes -->
<div class="container" id="boxes"></div>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#2.0.0-next.4/dist/umd/index.min.js" integrity="sha384-AWosBrv7t83vzfQDzCZrtcVWT9tFVGuP7uL1EqwhTLscYSCGShI9+FOYrSL1wQYT" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
</body>
</html>

For the first problem of having 18 divs instead of 9 in is because newGame method is called twice. One is at the end of code, the other one is in this line:
// Listener for reset button
buttonReset.addEventListener("click", resetGame());
The resetGame method is called there but it should be just passed as it is:
buttonReset.addEventListener("click", resetGame);
For the second problem of resetGame method not working as expected is that you are modifying the array that is being accessed (container.childNodes) in the loop.
That makes your i skip the element next to the each removed one.
Your difficulty may eventually become larger than childNodesCount
One solution is that do not remove items immediately, accumulate them in an array array and then remove based on that array
const toBeRemoved = []
for (let i = 0; i < difficulty; i++) {
toBeRemoved.push(container.childNodes[i]);
}
toBeRemoved.forEach(child => {
container.removeChild(child);
})
OR, another solution is that copy the childNodes to another variable so when you modify the original childNodes the copied array does not get affected:
const arrayOfChildren = Array.from(container.childNodes)
for (let i = 0; i < difficulty; i++) {
container.removeChild(arrayOfChildren[i]);
}
After fixing both problems:
var buttonReset = document.querySelector("#reset");
var container = document.querySelector("#boxes");
var difficulty = 9;
var h1 = document.querySelectorAll("h1");
var message = document.querySelector("#message");
var pickedColor = "";
// Listener for reset button
buttonReset.addEventListener("click", resetGame);
function newGame() {
// Create div elements inside container according to difficulty
for (let i = 0; i < difficulty; i++) {
container.appendChild(createDiv());
}
// Select all squares.
var squares = document.querySelectorAll(".square");
// Create and fill colors array
let colors = createColors();
// Pick a random color from colors
pickedColor = colors[
Math.floor(Math.random() * squares.length)
];
// Update text on screen
colorDisplay.textContent = pickedColor;
// Draw squares with colors and check clicked color.
for (let i = 0; i < squares.length; i++) {
// Add initial colors to squares
squares[i].style.backgroundColor = colors[i];
// Add click events to squares
squares[i].addEventListener("click", function() {
// check if clickedColor is pickedColor.
if (this.style.backgroundColor === pickedColor) {
message.textContent = "Yes, you've found the color";
//change all square colors to pickedColor
for (let i = 0; i < difficulty; i++) {
// Add initial colors to squares
squares[i].style.backgroundColor = pickedColor;
};
h1.forEach(function(item) {
item.style.backgroundColor = pickedColor;
});
} else {
message.textContent = "Please try again!"
this.style.backgroundColor = "#232323";
}
});
};
}
function createColors() {
let createdList = [];
for (let i = 0; i < difficulty; i++) {
createdList.push("rgb(" +
Math.floor(Math.random() * 256) + ", " +
Math.floor(Math.random() * 256) + ", " +
Math.floor(Math.random() * 256) + ")");
};
return createdList;
};
function createDiv() {
// create a div element and assign "square" class
let div = document.createElement("div");
div.classList.toggle("square");
return div;
};
function resetGame() {
/// Clean boxes
const arrayOfChildren = Array.from(container.childNodes)
for (let i = 0; i < difficulty; i++) {
container.removeChild(arrayOfChildren[i]);
}
// Create new game
newGame();
};
newGame(); // Only for first run
body {
background-color: #232323;
}
h1 {
color: white;
}
.square {
background: greenyellow;
float: left;
margin: 1.66%;
padding-bottom: 30%;
width: 30%;
}
#container {
margin: 0 auto;
max-width: 800px;
}
#stripe {
background: white;
color: black;
height: 30px;
text-align: center;
}
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<title>Color Game</title>
</head>
<body>
<h1 class="display-4">THE GREAT</h1>
<h1 class="display-2"><span id="colorDisplay">RGB(175, 203, 2)</span></h1>
<h1 class="display-4">GUESSING GAME</h1>
<div id="stripe">
<button id="reset">NEW COLORS</button>
<span id="message"></span>
</div>
<!-- Color boxes -->
<div class="container" id="boxes"></div>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#2.0.0-next.4/dist/umd/index.min.js" integrity="sha384-AWosBrv7t83vzfQDzCZrtcVWT9tFVGuP7uL1EqwhTLscYSCGShI9+FOYrSL1wQYT" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
</body>
</html>

Related

How can I get the size of the grid to stay the same regardless of the number of divs inside (the new number i enter)?

I am working on The Odin Project and I am on the etch-a-sketch section. I believe I have every part working except resizing the grid when a new number is entered. Any help would be greatly appreciated.
const container = document.getElementById("container");
const button = document.querySelector("input");
button.addEventListener('click', ()=> {
numOfSquares();
})
function numOfSquares() {
if (button.value === "number of squares") {
let newNumPerRow = prompt("how many squares per side would you like?", "");
let parse = parseInt(newNumPerRow);
makeRows(parse);
}
}
function hoverColor() {
let items = document.querySelectorAll('.gridItems');
items.forEach(item => {
item.addEventListener('mouseover', () => {
item.style.backgroundColor = 'orange';
});
});
}
function clearGrid() {
const gridArray = Array.from(container.childNodes);
gridArray.forEach(element => {
container.removeChild(element);
})
}
function makeRows (numberPerRow) {
clearGrid();
const total = (numberPerRow * numberPerRow) + numberPerRow;
const box = numberPerRow + 1;
for (i=0; i < total; i++) {
const div = document.createElement('div');
container.appendChild(div).className = "gridItems";
if (i % box === 0) {
div.style.cssText = "border: 0; height: 0; width: 100%";
} else {
div.style.cssText = "border: 1px solid black; height: 25px; width: 25px";
}
}
hoverColor();
}
makeRows(16);
I have tried to change the inline div style in javascript portion underneath the makeRows function, but nothing seems to work. Unless I completely miss something.
CSS
* {
box-sizing: border-box;
}
#container {
display: flex;
flex-wrap: wrap;
justify-content: center;
}
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 Project</title>
<link rel="stylesheet" href="style.css">
<script src="index.js" defer></script>
</head>
<body>
<input type="button" value="number of squares">
<div id="container">
</div>
</body>
</html>
I'm not familiar with the project exactly, but taking a look at your js, it looks like you're hard-coding the width value for the elements. Something like this may be helpful if you need to use flex:
function makeRows(numberPerRow) {
clearGrid();
const total = numberPerRow * numberPerRow + numberPerRow;
const box = numberPerRow + 1;
for (i = 0; i < total; i++) {
const div = document.createElement("div");
container.appendChild(div).className = "gridItems";
if (i % box === 0) {
div.style.cssText = "border: 0; height: 0; width: 100%";
} else {
//dynamically resize?
div.style.cssText = `border: 1px solid black; height: ${
1000 / numberPerRow
}px; width: ${1000 / numberPerRow}px`;
//dynamically resize?
}
}
hoverColor();
}
Since you are making a grid though, it may be more helpful to use grid layout rather than flex.
https://developer.mozilla.org/en-US/docs/Web/CSS/grid
https://www.w3schools.com/css/css_grid.asp
I'm giving you a solution using display: grid as this is the preferred method to use when creating a grid (it's in the name).
I left the HTML the exact same.
const container = document.getElementById("container");
const button = document.querySelector("input");
button.addEventListener('click', ()=> {
numOfSquares();
})
function numOfSquares() {
if (button.value === "number of squares") {
let newNumPerRow = prompt("how many squares per side would you like?", "");
let parse = parseInt(newNumPerRow);
makeRows(parse);
}
}
function hoverColor() {
let items = document.querySelectorAll('.gridItems');
items.forEach(item => {
item.addEventListener('mouseover', () => {
item.style.backgroundColor = 'orange';
});
});
}
function clearGrid() {
const gridArray = Array.from(container.childNodes);
gridArray.forEach(element => {
container.removeChild(element);
})
}
function makeRows (numberPerRow) {
clearGrid();
//Set the grid template columns straight from JavaScript
container.style.gridTemplateColumns = `repeat(${numberPerRow}, 1fr)`;
//Resolved an issue here that was adding an extra row
const total = numberPerRow * numberPerRow;
//Idk what the point of box was so I removed it for the sake of the answer
for (i = 0; i < total; i++) {
const div = document.createElement('div');
container.appendChild(div).className = "gridItems";
//Moved the gridItem styling to CSS
}
hoverColor();
}
makeRows(16);
* {
box-sizing: border-box;
}
#container {
display: grid;
width: 100%; /* Set whichever width you want here */
aspect-ratio: 1/1;
}
.gridItems {
border: 1px solid black;
}
<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 Project</title>
<link rel="stylesheet" href="style.css">
<script src="index.js" defer></script>
</head>
<body>
<input type="button" value="number of squares">
<div id="container">
</div>
</body>
</html>
Add this at the top of you js and specify the size of your grid in px. You can add it to makeRows as a variant:
const preservedWidth = 600;
Also add boxWidth to makeRows to calculate the width of your grid element:
const boxWidth = preservedWidth / numberPerRow;
Change this:
div.style.cssText = "border: 1px solid black; height: 25px; width: 25px";
to:
div.style.cssText = `border: 1px solid black; height: ${boxWidth}; width: ${boxWidth}`;
This is the whole JS code:
const container = document.getElementById("container");
const button = document.querySelector("input");
const preservedWidth = 300;
button.addEventListener('click', ()=> {
numOfSquares();
})
function numOfSquares() {
if (button.value === "number of squares") {
let newNumPerRow = prompt("how many squares per side would you like?", "");
let parse = parseInt(newNumPerRow);
makeRows(parse);
}
}
function hoverColor() {
let items = document.querySelectorAll('.gridItems');
items.forEach(item => {
item.addEventListener('mouseover', () => {
item.style.backgroundColor = 'orange';
});
});
}
function clearGrid() {
const gridArray = Array.from(container.childNodes);
gridArray.forEach(element => {
container.removeChild(element);
})
}
function makeRows (numberPerRow) {
clearGrid();
const total = (numberPerRow * numberPerRow) + numberPerRow;
const box = numberPerRow + 1;
const boxWidth = preservedWidth / numberPerRow;
for (i=0; i < total; i++) {
const div = document.createElement('div');
container.appendChild(div).className = "gridItems";
if (i % box === 0) {
div.style.cssText = "border: 0; height: 0; width: 100%";
} else {
div.style.cssText = `border: 1px solid black; height: ${boxWidth}; width: ${boxWidth}`;
}
}
hoverColor();
}
makeRows(16);

How to create a jQuery selection which is a random sample of another jQuery selection?

This question is similar to How to get random element in jquery?, except that instead of a single randomly selected element, I would like to get a subset of k distinct, randomly sampled elements (similar to Python's random.sample).
For inputs which are arrays instead of jQuery objects, I came up with the following:
function randomSample(arr, k) {
var arr = arr.slice(); // Work with a copy of the original array
var samples = [];
var i;
for (i = 0; i < k; i++) {
randomIndex = Math.floor(Math.random() * arr.length);
samples.push(arr.splice(randomIndex, 1)[0]);
}
return samples;
}
I would like to adapt this function to the case where the input is a jQuery object instead of an array. However, I'm struggling with this because I can't find a way to create an 'empty' jQuery object and 'push' elements to it.
What I'm doing now is altering the selected element (by adding a class "yellow" to it) and then re-running a jQuery selector with not.(".yellow") in order to sample without replacement. Here is a snippet (adapted from https://api.jquery.com/slice/):
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>slice demo</title>
<style>
div {
width: 40px;
height: 40px;
margin: 10px;
float: left;
border: 2px solid blue;
}
span {
color: red;
font-weight: bold;
}
button {
margin: 5px;
}
.yellow {
background: yellow;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<p><button>Turn slice yellow</button>
<span>Click the button!</span></p>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<script>
function colorEm(k) {
var $div = $("div");
$div.removeClass("yellow");
var i;
for (i = 0; i < k; i++) {
var $notYetHighlighted = $("div").not(".yellow");
var start = Math.floor(Math.random() * $notYetHighlighted.length);
var end = start + 1;
if (end === $notYetHighlighted.length) {
end = undefined;
}
if (end) {
$notYetHighlighted.slice(start, end).addClass("yellow");
} else {
$notYetHighlighted.slice(start).addClass("yellow");
}
}
}
$( "button" ).click( function() { colorEm(3) } );
</script>
</body>
</html>
Is this 'modifying and re-querying' paradigm the only way to randomly sample a jQuery object?
i rewrite your script to jquery function. I think it's easy to change it later.
/**
* MyFunction to highliting div
*/
$.fn.myFunctionName = function(e) {
let num = e.data.num;
let bgCss = "yellow";
let elements = $('div');
elements.removeClass(bgCss); // remove highlight class from all divs
function doHighlite() {
let randomSquere = Math.floor(Math.random() * elements.length); // get random element index
// add class if not exist or try generate next element
if(!$(elements[randomSquere]).hasClass(bgCss)) {
$(elements[randomSquere]).addClass(bgCss);
}
else {
doHighlite();
}
};
// highlight desired number of elements
for(let i=0; i<num;i++) {
doHighlite();
}
}
And you can run it with parameter num
$(".red").on('click', { num: 5 }, $.fn.myFunctionName);
JSFIDDLE DEMO

JavaScript color game default colors

So I am doing a color picking game with JavaScript. I have the functionality of everything working perfectly. But I noticed a bug. When you first load onto the page or even refresh the page. The values of all squares are purple. If you click new colors or hard or the easy button different rgb values are populating. Why am I getting a default of purple values when I start the page or refresh? I am trying to have it so when the page is started it randomizes the rgb values without me or the user having to hit new colors to initiate the game.
heres my code
~html
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="index.css">
<title>Color Game!</title>
</head>
<body>
<h1>The Great <span id="colorDisplay">RGB</span> Color Game</h1>
<div id="stripe">
<button id="reset">New Colors</button>
<span id="message"></span>
<button id="easyBtn">Easy</button>
<button id="hardBtn" class="selected">Hard</button>
</div>
<div id="container">
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
</div>
<script type="text/javascript" src="index.js"></script>
</body>
</html>
~css
body {
background-color: #232323;
margin: 0;
font-family: "Montserrat", "Avenir";
}
.square {
width: 30%;
background: purple;
padding-bottom: 30%;
float: left;
margin: 1.66%;
}
#container {
max-width: 600px;
margin: 0 auto;
}
h1 {
text-align: center;
font-weight: normal;
color: white;
background-color: steelblue;
margin: 0;
}
#stripe {
background-color: white;
height: 30px;
text-align: center;
color: black;
}
.selected {
background: blue;
}
~ JS
var colors = generateRandomColors(numSquares);
var numSquares = 6;
var squares = document.querySelectorAll(".square");
var h1 = document.querySelector("h1");
var pickedColor = pickColor();
var colorDisplay = document.getElementById("colorDisplay");
var messageDisplay = document.querySelector("#message");
var resetButton = document.querySelector("#reset");
var easyBtn = document.getElementById("easyBtn");
var hardBtn = document.getElementById("hardBtn");
easyBtn.addEventListener("click", function(){
hardBtn.classList.remove("selected");
easyBtn.classList.add("selected");
numSquares = 3;
colors = generateRandomColors(numSquares);
pickedColor = pickColor();
colorDisplay.textContent = pickedColor;
for(var i = 0; i < squares.length; i++) {
if(colors[i]) {
squares[i].style.backgroundColor = colors[i];
} else {
squares[i].style.display = "none";
}
}
})
hardBtn.addEventListener("click", function(){
hardBtn.classList.add("selected");
easyBtn.classList.remove("selected");
numSquares = 6;
colors = generateRandomColors(numSquares);
pickedColor = pickColor();
colorDisplay.textContent = pickedColor;
for(var i = 0; i < squares.length; i++) {
squares[i].style.backgroundColor = colors[i];
squares[i].style.display = "block";
}
})
resetButton.addEventListener("click", function(){
// generate all new colors
colors = generateRandomColors(numSquares);
// pick a new random color from the array
pickedColor = pickColor();
// change colorDisplay to match picked color
colorDisplay.textContent = pickedColor;
// change colors of squares
for(var i = 0; i < squares.length; i++) {
squares[i].style.backgroundColor = colors[i];
}
h1.style.backgroundColor = "steelblue";
})
colorDisplay.textContent = pickedColor;
for(var i = 0; i < squares.length; i++) {
// add initial colors to squares
squares[i].style.backgroundColor = colors[i];
// add click listeners to squares
squares[i].addEventListener("click", function(){
// grab color of clicked square
var clickedColor = this.style.backgroundColor;
// compare color to pickedColor
if(clickedColor === pickedColor){
messageDisplay.textContent = "Correct!";
resetButton.textContent = "Play Again?";
changeColors(clickedColor);
h1.style.backgroundColor = clickedColor;
} else {
this.style.backgroundColor = "#232323";
messageDisplay.textContent = "Try Again";
}
});
}
function changeColors(color) {
//loop through all squares
for(var i = 0; i < squares.length; i++) {
squares[i].style.backgroundColor = color;
}
}
function pickColor() {
var random = Math.floor(Math.random() * colors.length);
return colors[random];
}
function generateRandomColors(num) {
// make an array
var arr = [];
// repeat num times
for(var i = 0; i < num; i++) {
arr.push(randomColor());
}
return arr;
}
function randomColor() {
// pick a "red" from 0 - 255
var r = Math.floor(Math.random() * 256);
// pick a "green" from 0 - 255
var g = Math.floor(Math.random() * 256);
// pick a "blue" from 0 - 255
var b = Math.floor(Math.random() * 256);
return "rgb(" + r + ", " + g + ", " + b + ")";
}
Your CSS hard codes the purple:
.square {
width: 30%;
background: purple;
You need to add an event handler for when the page loads to call your color changing code like this:
window.addEventListener("DOMContentLoaded", function(){
// Call color changing code here
});
Make sure numSquares is declared before colors.
So
var colors = generateRandomColors(numSquares);
var numSquares = 6;
becomes
var numSquares = 6;
var colors = generateRandomColors(numSquares);

Auto-Play feature not executing in JS

I have somewhat of a baseball game, obviously there are not bases or hits. Its all stikes, balls and outs. The buttons work and the functionality of the inning (top and bottom as well as count) are working. I want this to ideally randomly throw a pitch on its own every few seconds. Basically to randomly "click" the ball or strike button. I am trying to use the setTimeout function with no success. Any help?
HTML:
<!DOCTYPE HTML>
<html>
<head>
<link rel="stylesheet" type="text/css" href="bullpen.css">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Bullpen</title>
</head>
</html>
<body>
<button id=buttons onclick="playBall()">Auto-Play</button>
<h2>Inning: <span id=inningHalf></span> <span id=inningNum></span></h2>
<div id=buttons>
<button onclick="throwBall(), newInning()">Ball</button>
<button onclick="throwStrike(), newInning()">Strike</button>
</div>
<h2>Count: <span id=ball>0</span> - <span id=strike>0</span></h2>
<h2>Outs: <span id=out>0</span></h2>
<h2>----------------</h2>
<h2>Walks: <span id=walks>0</span></h2>
<h2>Strikeouts: <span id=strikeout>0</span></h2>
<script src="bullpen.js"></script>
</body>
</html>
JS:
var ball = 0;
var strike = 0;
var out = 0;
var walks = 0;
var strikeout = 0;
//---------------------------------
var outPerInning = 0;
var inning = 1;
//---------------------------------
document.getElementById('inningNum').innerHTML = inning;
document.getElementById('inningHalf').innerHTML = '▲';
function throwBall(){
ball++;
document.getElementById('ball').innerHTML = ball;
if (ball == 4){
ball = 0;
strike = 0;
walks++;
document.getElementById('walks').innerHTML = walks;
document.getElementById('strike').innerHTML = 0;
document.getElementById('ball').innerHTML = 0;
}
};
function throwStrike(){
strike++;
document.getElementById('strike').innerHTML = strike;
if(strike == 3){
ball = 0;
strike = 0;
strikeout++;
out++;
outPerInning++;
document.getElementById('strikeout').innerHTML = strikeout;
document.getElementById('out').innerHTML = out;
document.getElementById('strike').innerHTML = 0;
document.getElementById('ball').innerHTML = 0;
}
};
function newInning(){
if(out == 3){
ball=0;
strike=0;
out=0;
document.getElementById('strike').innerHTML = 0;
document.getElementById('ball').innerHTML = 0;
document.getElementById('out').innerHTML = 0;
}
if(outPerInning == 3){
document.getElementById('inningHalf').innerHTML = '▼';
}
if(outPerInning == 6){
inning++;
document.getElementById('inningHalf').innerHTML = '▲';
outPerInning = 0;
document.getElementById('inningNum').innerHTML = inning;
}
};
function playBall(){
var play = Math.random;
if(play >= 0.4){
throwStrike();
newInning();
}
else{
throwBall();
newInning();
}
setTimeout(playBall, 5000);
};
CSS if needed:
h2{
margin-left: 50px;
font-size: 50px;
}
button{
font-size: 45px;
}
#buttons{
width: 227px;
margin-left:50px;
margin-top: 20px;
}
Perhaps this is the problem:
function playBall(){
var play = math.random;
if(play >= 0.4){
throwStrike;
newInning();
}
else{
throwBall;
newInning();
}
setTimeout(playBall, 5000);
};
Should be
function playBall(){
var play = Math.random();
if(play >= 0.4){
throwStrike(); //call the function
newInning();
}
else{
throwBall(); //call the function
newInning();
}
setTimeout(playBall, 5000);
};
You were not calling these functions!
Here is a working fiddle: https://jsfiddle.net/av6vsp7g/

JavaScript/HTML div creation error

I am trying to make a basic sensor pad for HTML (JavaScript), which creates 500 small divs which then turn red on mouse hover. However, when I tried it, nothing was created
example.html
<!DOCTYPE html>
<html>
<head>
<title>SensorPad Test</title>
<link rel="stylesheet" href="styles.css" type="text/css">
<script type="text/javascript" src="SensorPad.js">
window.onload = createSensor;
</script>
</head>
</html>
styles.css
.sPad{
width: 0.4px;
height: 0.4px;
background-color: #EEE;
border: 0.1px solid #000;
}
.uPad{
background-color: #F00;
}
SensorPad.js
var sPos;
var count = 1;
function createSensor(){
for(var i = 0; i < 500; ++i){
var pad = document.createElement('div');
pad.className = 'sPad';
pad.id = 'pad' + count.toString();
pad.onmousehover = function(){sPos = parseInt(pad.id); clearPads(); pad.className = 'uPad';};
count++;
}
}
function clearPads(){
for(var i = 1; i <= count; ++i){
var n = 'pad' + i.toString();
var p = document.getElementById(n);
p.className = 'sPad';
}
}
You're missing
document.body.appendChild(pad);
First the code will not run because of the way you added the JavaScript
<script type="text/javascript" src="SensorPad.js">
window.onload = createSensor;
</script>
you can not have code inside and a src
<script type="text/javascript" src="SensorPad.js"></src>
<script type="text/javascript"
window.onload = createSensor;
</script>
First, you need to use separate script tags - one for the external reference and another for the onload.
As for the divs, you're creating them but you're not adding them to the DOM.
for(var i = 0; i < 500; ++i){
var pad = document.createElement('div');
pad.className = 'sPad';
pad.id = 'pad' + count.toString();
pad.onmousehover = function(){sPos = parseInt(pad.id); clearPads(); pad.className = 'uPad';};
document.body.appendChild(pad)
count++;
}
EDIT: Addressing Teemu's concern you might simply want to use CSS for that hover instead so:
for(var i = 0; i < 500; ++i){
var pad = document.createElement('div');
pad.className = 'sPad';
pad.id = 'pad' + i.toString();
document.body.appendChild(pad)
}
css
.sPad{
width: 0.4px;
height: 0.4px;
background-color: #EEE;
border: 0.1px solid #000;
}
.sPad:hover{
background-color: #F00;
}

Categories

Resources