How to create containers all at the same time with random colours? - javascript

my following code essentially creates a number of boxes according to the input of the user.
However i want to ensure that when they are created, they all have a random colour.
I also want to ensure that for each new box created, it sets the margin-left of the box to be double the previous box’s margin (where the first box has margin-left 5px).
I have no idea how to do this!
function getNewRandomColor()
{
var myArray = ['red', 'green', 'blue'];
var rand = myArray[Math.floor(Math.random() * myArray.length)];
document.getElementById("container").style.backgroundColor = rand;
}
var empty = true;
function setup()
{
if (!empty)
{
remove();
}
size = document.getElementById("input").value
var container = document.getElementById("container");
// create boxes
for (var i = 0; i < size; i++)
{
// Create a box
var box = document.createElement("div");
// insert number
box.innerHTML = i+1;
// Add into the document
container.appendChild(box);
empty = false;
}
}
function remove()
{
// Get all the generated boxes
var boxes = document.getElementById("container").children;
// Iterate through all boxes
for (var x = 0; x < boxes.length;)
{
var bA = boxes[x];
bA.remove();
}
}
body {
font-family:sans-serif;
font-weight:700;
font-size:15pt;
}
#container div, div.selected {
width: 2em;
height: 1.5em;
float: left;
padding: 1em;
margin: 1vw;
padding-top:1.5em;
text-align: center;
transition: background 1s;
}
div, .unselected {
background: #a0aeef;
}
<input type="number" name="input" id="input">
<button onclick="setup();">Draw</button>
<button onclick="remove();">Remove</button>
<div id="container"></div>

You could only retrieve the array key and use it as a classname, style on the fly can be applied once the element is part of the dom of the document :
ex
function getNewRandomColor(e)
{
var myArray = ['red', 'green', 'blue'];
var rand = myArray[Math.floor(Math.random() * myArray.length)];
return rand;
}
var empty = true;
function setup()
{
if (!empty)
{
remove();
}
size = document.getElementById("input").value
var container = document.getElementById("container");
// create boxes
for (var i = 0; i < size; i++)
{
// Create a box
var box = document.createElement("div");
var rdmClass= getNewRandomColor();
box.setAttribute("class",rdmClass);
marginVar = 10*i;
box.setAttribute("style","--margR:" + marginVar + ";border:solid/* here you bg with hex value to be updated " );
// insert number
box.innerHTML = i+1;
// Add into the document
container.appendChild(box);
empty = false;
}
}
function remove()
{
// Get all the generated boxes
var boxes = document.getElementById("container").children;
// Iterate through all boxes
for (var x = 0; x < boxes.length;)
{
var bA = boxes[x];
bA.remove();
}
}
body {
font-family:sans-serif;
font-weight:700;
font-size:15pt;
}
#container div, div.selected {
width: 2em;
height: 1.5em;
float: left;
padding: 1em;
margin: 1vw;
padding-top:1.5em;
text-align: center;
transition: background 1s;
}
div, .unselected {
background: #a0aeef;
}
#container div{
margin-right:calc(var(--margR)*1px); /* updated from the style attribute added from js loop */
}
.red {background:red;}
.green {background:green;}
.blue {background:blue;}
<input type="number" name="input" id="input">
<button onclick="setup();">Draw</button>
<button onclick="remove();">Remove</button>
<div id="container"></div>

Related

Can't assign a specific color to div even though I defined the color earlier

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 get back to global scope after running a function in JavaScript?

When starting my program, everything initially runs as intended. However, when I click a button on the webpage that runs my clearBoard() function, the code in the global scope no longer runs.
I've used console.log and everything that is outside of a function is empty after running the clearBoard().
const container = document.getElementById("container");
//Create board
function makeRows(rows, columns) {
//let container = document.getElementById("container");
container.style.setProperty('--grid-rows', rows);
container.style.setProperty('--grid-cols', columns);
for (c = 0; c < (rows * columns); c++) {
let cell = document.createElement("div");
//cell.innerText = (c + 1);
container.appendChild(cell).className = "grid-item";
}
}
//Draw starting Board
makeRows(16, 16);
//Paint on board
const paint = document.getElementsByClassName("grid-item");
console.log(container);
for (let i = 0; i < paint.length; i++) {
paint[i].addEventListener('mouseover', function() {
this.style.backgroundColor = "black";
});
}
//Get new board size
function getNewBoard() {
//clear divs
const removeOldGrid = document.getElementById("container");
removeOldGrid.innerHTML = '';
//get input from user
let squares = prompt('How many squares per side?');
//convert input to number
let squaresInt = parseInt(squares);
//generate new board
makeRows(squaresInt, squaresInt);
}
//Clear board
function clearBoard() {
for (let i = 0; i < paint.length; i++) {
paint[i].style.backgroundColor = "";
}
getNewBoard();
}
:root {
--grid-cols: 0;
--grid-rows: 0;
--paint-color: ;
}
#container {
display: grid;
padding: 10em;
height: 40vh;
width: 50vh;
margin-left: auto;
margin-right: auto;
/*grid-gap: 1em;*/
grid-template-rows: repeat(var(--grid-rows), 1fr);
grid-template-columns: repeat(var(--grid-cols), 1fr);
}
.grid-item {
padding: 1em;
border: 1px solid #ddd;
text-align: center;
/*background-color: var(--paint-color);*/
}
/*.grid-item:hover {
background-color: black;
}
<button onclick="clearBoard()">Clear Board</button>
<div id="container">
</div>
That is happening because you are creating a new board, consequently a new grid-item element. The mouseover event listener is added to the paint variable, which contains the old element after clearBoard() is called.
The solution is to add a new event listener to paint when a new board is generated. Your JS should look something like this:
//Paint on board
var paint = document.getElementsByClassName("grid-item");
console.log(container);
// Function to add the mouseover event listener when "paint" changes
function addMouseoverEventListener() {
for (let i = 0; i < paint.length; i++)
{
paint[i].addEventListener('mouseover', function() {
this.style.backgroundColor = "black";
});
}
}
addMouseoverEventListener();
//Get new board size
function getNewBoard() {
//clear divs
const removeOldGrid = document.getElementById("container");
removeOldGrid.innerHTML = '';
//get input from user
let squares = prompt('How many squares per side?');
//convert input to number
let squaresInt = parseInt(squares);
//generate new board
makeRows(squaresInt, squaresInt);
// Get the new element
paint = document.getElementsByClassName("grid-item");
// Add the event listener again
addMouseoverEventListener();
}
Instead of using paint[i].addEventListener use window.onmouseover and check the target
const container = document.getElementById("container");
//Create board
function makeRows (rows, columns) {
//let container = document.getElementById("container");
container.style.setProperty('--grid-rows', rows);
container.style.setProperty('--grid-cols', columns);
for (c = 0; c < (rows * columns); c++) {
let cell = document.createElement("div");
//cell.innerText = (c + 1);
container.appendChild(cell).className = "grid-item";
}
}
const paint = document.getElementsByClassName("grid-item");
//Draw starting Board
makeRows(16, 16);
window.onmouseover=function(e) {
if(e.target.className == "grid-item")
{
e.target.style.backgroundColor = "black";
}
};
//Get new board size
function getNewBoard() {
//clear divs
const removeOldGrid = document.getElementById("container");
removeOldGrid.innerHTML = '';
//get input from user
let squares = prompt('How many squares per side?');
//convert input to number
let squaresInt = parseInt(squares);
//generate new board
makeRows(squaresInt, squaresInt);
}
function clearBoard() {
for (let i = 0; i < paint.length; i++) {
paint[i].style.backgroundColor = "";
}
getNewBoard();
}
:root {
--grid-cols: 0;
--grid-rows: 0;
--paint-color: ;
}
#container {
display: grid;
padding: 10em;
height: 40vh;
width: 50vh;
margin-left: auto;
margin-right: auto;
/*grid-gap: 1em;*/
grid-template-rows: repeat(var(--grid-rows), 1fr);
grid-template-columns: repeat(var(--grid-cols), 1fr);
}
.grid-item {
padding: 1em;
border: 1px solid #ddd;
text-align: center;
/*background-color: var(--paint-color);*/
}
/*.grid-item:hover {
background-color: black;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Etch-a-Sketch</title>
<meta name="author" content="">
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="style.css" rel="stylesheet">
</head>
<body>
<button onclick = "clearBoard()">Clear Board</button>
<div id="container">
</div>>
<script src="script.js"></script>
</body>
</html>

DOM assign an id to child Javascript

I have created a grid with div, class and id. I want to randomly create a yellow square and I want to assign an id= 'yellowSquare' how do I do it?
var grid = document.getElementById("grid-box");
for (var i = 1; i <= 100; i++) {
var square = document.createElement("div");
square.className = 'square';
square.id = 'square' + i;
grid.appendChild(square);
}
var playerOne = [];
while (playerOne.length < 1) {
var randomIndex = parseInt(99 * Math.random());
if (playerOne.indexOf(randomIndex) === -1) {
playerOne.push(randomIndex);
var drawPone = document.getElementById('square' + randomIndex);
drawPone.style.backgroundColor = 'yellow';
}
}
#grid-box {
width: 400px;
height: 400px;
margin: 0 auto;
font-size: 0;
position: relative;
}
#grid-box>div.square {
font-size: 1rem;
vertical-align: top;
display: inline-block;
width: 10%;
height: 10%;
box-sizing: border-box;
border: 1px solid #000;
}
<div id="grid-box"></div>
I am new to Javascript / jQuery. Any help will be much appreciated ! Thank you
There are two options to your question. You can either change the id of the yellow square which is already created from your code, or create a child element within the square, which looks the same as your current solution. Creating a new child element will let you keep the numeric id pattern for the grid:
Changing the ID :
var element = document.getElementById('square' + randomIndex)
element.id = "yellowSquare";
Adding new element inside:
var node = document.createElement("DIV");
node.id = "yellowSquare";
node.style = "background-color:yellow;height:100%;width:100%;";
var element = document.getElementById('square' + randomIndex)
element.appendChild(node);
I set the styling of the div child to 100% width and height, as it has no content, and would get 0 values if nothing was specified. This should make it fill the parent container.
There are also multiple other ways to achieve the same result, for instance with JQuery.
Use the HTMLElement method setAttribute (source);
...
var drawPone = document.getElementById('square' + randomIndex);
drawPone.style.backgroundColor = 'yellow';
drawPone.setAttribute('id', 'yellowSquare');
...
As you requested in your comment how to move the square i made an example how you can move it left and right using jQuery next() and prev() functions. However because your html elements are 1 dimensional it's not easy to move them up/down and check the sides for collisions. Better would be to create your html table like with rows and columns and this way create a 2 dimensional play field.
Also added a yellowSquery class for selection with $drawPone.addClass('yellowSquare');.
Also since you like to use jQuery I changed your existing code to jQuery function. Might help you learn the framework.
var $grid = $("#grid-box");
for (var i = 1; i <= 100; i++) {
var $square = $("<div>");
$square.addClass('square');
$square.attr('id','square' + i);
$grid.append($square);
}
var playerOne = [];
while (playerOne.length < 1) {
var randomIndex = parseInt(99 * Math.random());
if (playerOne.indexOf(randomIndex) === -1) {
playerOne.push(randomIndex);
var $drawPone = $('#square' + randomIndex);
$drawPone.addClass('yellowSquare');
}
}
$('#button_right').on('click', function(){
$yellowSquare = $('.yellowSquare')
$yellowSquareNext = $yellowSquare.next();
$yellowSquare.removeClass('yellowSquare');
$yellowSquareNext.addClass('yellowSquare');
});
$('#button_left').on('click', function(){
$yellowSquare = $('.yellowSquare')
$yellowSquarePrev = $yellowSquare.prev();
$yellowSquare.removeClass('yellowSquare');
$yellowSquarePrev.addClass('yellowSquare');
});
#grid-box {
width: 400px;
height: 400px;
margin: 0 auto;
font-size: 0;
position: relative;
}
#grid-box>div.square {
font-size: 1rem;
vertical-align: top;
display: inline-block;
width: 10%;
height: 10%;
box-sizing: border-box;
border: 1px solid #000;
}
.yellowSquare {
background-color: yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="grid-box"></div>
<button id="button_left">left</button>
<button id="button_right">right</button><br>

Create a 10x10 field of cells

I want to create a field of cells. The field has a size of 10x10. When reaching a maximum count of cells in a row, it should start a new row.
Currently all my cell divs are placed below.
function initGame() {
var mapSize = 10; // create a field of 10x10
var cellsPerRow = 10; // 10 cells per row
for (var x = 0; x < mapSize; x++) {
for (var y = 0; y < mapSize; y++) {
createCell(x, y); // create a cell on index x (horizontal) and y (vertical)
}
}
}
function createCell(x, y) {
// store this cell position to a data class
var cellDiv = $("<div></div>"); // create the cell div
cellDiv.addClass("cell"); // add some css
$(document.body).append(cellDiv); // add the cell div to the parent
}
.cell{
height: 50px;
width: 50px;
border-style: solid;
border-width: 1px;
border-color: black;
background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body onLoad="initGame()">
</body>
Create wrapper for each 10 cell.
function initGame() {
var mapSize = 10; // create a field of 10x10
var cellsPerRow = 10; // 10 cells per row
for (var x = 0; x < mapSize; x++) {
$(document.body).append("<div>");
for (var y = 0; y < mapSize; y++) {
createCell(x, y); // create a cell on index x (horizontal) and y (vertical)
}
$(document.body).append("</div>");
}
}
function createCell(x, y) {
// store this cell position to a data class
var cellDiv = $("<div></div>"); // create the cell div
cellDiv.addClass("cell"); // add some css
$(document.body).append(cellDiv); // add the cell div to the parent
}
.cell{
height: 50px;
width: 50px;
border-style: solid;
border-width: 1px;
border-color: black;
background: red;
display: inline-block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body onLoad="initGame()">
</body>
use display:inline-block; for .cells and to stop 10 each row add a <br> tag after 10 divs in row.
function initGame() {
var mapSize = 10; // create a field of 10x10
var cellsPerRow = 10; // 10 cells per row
for (var x = 0; x < mapSize; x++) {
for (var y = 0; y < mapSize; y++) {
createCell(x, y);
}
$(document.body).append("<br>");
}
}
function createCell(x, y) {
// store this cell position to a data class
var cellDiv = $("<div></div>"); // create the cell div
cellDiv.addClass("cell"); // add some css
$(document.body).append(cellDiv); // add the cell div to the parent
}
.cell {
height: 50px;
width: 50px;
border-style: solid;
border-width: 1px;
border-color: black;
background: red;
display: inline-block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body onLoad="initGame()">
</body>
You can use absolute positioning and set for each of them css property. Here is the fiddle
function initGame() {
var mapSize = 10; // create a field of 10x10
var cellsPerRow = 10; // 10 cells per row
for (var x = 0; x < mapSize; x++) {
for (var y = 0; y < mapSize; y++) {
createCell(x, y); // create a cell on index x (horizontal) and y (vertical)
}
}
}
function createCell(x, y) {
// store this cell position to a data class
var cellDiv = $("<div></div>"); // create the cell div
cellDiv.addClass("cell"); // add some css
cellDiv.css({
left: Math.floor(x*50),
top: Math.floor(y*50)
});
$(document.body).append(cellDiv); // add the cell div to the parent
}
initGame()
.cell{
height: 50px;
width: 50px;
border-style: solid;
border-width: 1px;
border-color: black;
background: red;
position: absolute;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
You can create a row div that contains multiple cell div
function initGame() {
const rows = 10;
const columns = 10;
for(let r=0;r<rows;r++){
let row = createRow(r);
for(let c=0;c<columns;c++){
createCell(row, r, c);
}
}
}
function createRow(rowNumber){
let row = document.createElement('DIV');
row.className += ' row'
$(document.body).append(row);
return row;
}
function createCell(domRow, rowNumber, columnNumber){
let column = document.createElement('DIV');
column.className += ' cell';
$(domRow).append(column);
}
.cell{
height: 50px;
width: 50px;
border: 1px solid grey;
background: tomato;
display: inline-block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body onLoad="initGame()">
</body>

Create custom square grid using jquery

I am working on a project trying to make something resembling an etch-a-sketch. I have a 780x780px square, and I am trying to get a 16x16 grid, using a series of smaller square divs.
It is on this grid that I have the hover effect. I keep getting a 15x17 grid of square divs because the last square of the row won't fit. I have margins set to 1px and padding set to 0 so I figured that to fit 16 squares on a 780px wide row, it would require me to take into account the margins (15 1px margins) and from there I could divide (780-15) by 16, the number of squares I want.
That isn't working, and the next step of this project is to have a button where the user could input any number of squares for the row/column and have either a larger or smaller squared grid STILL ON the 780x780 square. Does anyone have any ideas? I'm pretty stumped.
$(document).ready(function() {
var original = 16;
for (var y = 0; y < original * original; y++) {
$(".squares").width((780 - 15) / original);
$(".squares").height((780 - 17) / original);
$("<div class='squares'></div>").appendTo('#main');
}
$('.squares').hover(
function() {
$(this).addClass('hover');
}
)
});
function gridq() {
$('.squares').removeClass('hover');
$('div').remove('.squares');
var newgrid = prompt("How many squares on each side?");
var widthscreen = 192;
if (newgrid > 0) {
for (var x = 0; x < newgrid * newgrid; x++) {
$(".squares").width(widthscreen / newgrid);
$(".squares").height(widthscreen / newgrid);
$("<div class='squares'></div>").appendTo('#main');
}
$('.squares').hover(
function() {
$(this).addClass('hover');
}
)
}
}
#main {
height: 780px;
width: 780px;
background-color: antiquewhite;
position: relative;
}
.squares {
margin: 1px;
padding: 0;
background-color: aquamarine;
display: inline-block;
float: left;
}
.hover {
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id=main>
</div>
<button onclick="gridq()">Go Again!</button>
Try this snippet? Grid initialisation is set in the grid() function and then called later when necessary. The width is set dynamically to the 16th square's right side.and the remaining squares fill out as necessary.
var wide = (780 - 15) / 16,
tall = (780 - 17) / 16; // set the square dimensions. this can be incorporated into the grid() function with 16 replaced by 'original'
function grid(x, y) {
var original = x,
y = y;
$("#main").empty(); // empty and restart
$("#main").width(wide * (original + 1));
for (var i = 0; i < original * y; i++) {
$("<div class='squares'></div>").appendTo('#main');
}
var square = $(".squares");
square.width(wide);
square.height(tall);
var side = square.eq(original - 1).position().left + square.width() + 2; // tighten the #main width
$("#main").width(side);
$('.squares').hover(
function() {
$(this).addClass('hover');
}
)
}
grid(16, 16); // starting dimension
function gridq() {
$('.squares').removeClass('hover');
$('div').remove('.squares');
var newgrid = prompt("How many squares on each side?");
var widthscreen = 192;
if (newgrid > 0) {
grid(newgrid, newgrid);
}
}
#main {
background-color: antiquewhite;
position: relative;
}
.squares {
margin: 1px;
padding: 0;
background-color: aquamarine;
display: inline-block;
float: left;
}
.hover {
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id='main'>
</div>
<button onclick="gridq()">Go Again!</button>
just got beat to it...ill post this as it answers the question slightly differently and I feel is a little cleaner. Also I added in a width and a height prompt.
see the codepen here
As a side note...its good practice to make the names of your variables make sense. Also I find that breaking down your code problems into smaller more manageable chunks makes it seem less overwhelming...one step at a time :)
Enjoy and good luck!
$(document).ready(function() {
//declare the variables at the top of your functions...it enables us to change them later
var columnWidthCount = 16;
var columnHeightCount = 16;
function makeBoxes() {
//boxcount lets us set how many times we want the for loop to run...when we change the columns/rows later this variable will be updated
var boxCount = columnWidthCount * columnHeightCount;
//
for (var i = 0; i < boxCount; i++) { //loop through each box
//any code you place in here will execute each time we loop around
$("<div class='squares'></div>").appendTo('#main');
}
//we only want to declare this once so we place it after the loop
$(".squares").width((780 / columnWidthCount) - 2);
$(".squares").height((780 / columnHeightCount) - 2);
$('.squares').hover(
function() {
$(this).addClass('hover');
}
);
}
//fire the initial function
makeBoxes();
// fire function after click
$('button').on("click", function() {
$('div').remove('.squares');
var squaresHigh = prompt("How many squares high? (must be a number)");
var squaresWide = prompt("How many squares wide? (must be a number)");
//prompt returns a string...use parseInt to turn that number string into an integer
columnWidthCount = parseInt(squaresWide);
columnHeightCount = parseInt(squaresHigh);
makeBoxes();
});
});
#main {
height: 780px;
width: 780px;
background-color: antiquewhite;
position: relative;
font-size:0;
white-space:nowrap;
}
.squares {
margin: 1px;
padding: 0;
background-color: aquamarine;
display: inline-block;
float: left;
}
.hover {
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id=main>
</div>
<button>Go Again!</button>

Categories