Reputation: 419
I'm trying to make a color black and then a color white, but some colors come together horizontally, and I didn't want it to stay that way. I want to create a board from a loop.
Could anyone help?
var tab = document.querySelector('.grid-container')
for (let i = 1; i <= 64; i++) {
if (i % 3 == 0) {
tab.innerHTML += '<div class="grid-item black">'+i+'</div>'
} else {
tab.innerHTML += '<div class="grid-item white">'+i+'</div>'
}
}
.grid-container {
display: grid;
grid-template-columns: repeat(8, 50px);
grid-template-rows: repeat(8, 50px);
background-color: #2196F3;
}
.grid-item {
background-color: rgba(255, 255, 255, 0.8);
border: 1px solid rgba(0, 0, 0, 0.8);
font-size: 30px;
text-align: center;
}
.black{
background-color: black;
}
.white {
background-color: white;
}
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="./css/style.css">
<title>Document</title>
</head>
<body>
<div class="grid-container">
</div>
<script src="./board.js"></script>
</body>
</html>
Upvotes: 0
Views: 66
Reputation: 43983
Use a second for
loop to easily distinguish rows and cols.
Then we can use the following if
to check for black/white squares:
if ((i + j) % 2) {
tab.innerHTML += '<div class="grid-item black">'+n+'</div>'
} else {
tab.innerHTML += '<div class="grid-item white">'+n+'</div>'
}
var tab = document.querySelector('.grid-container')
for (let i = 0; i < 8; i++) {
for (let j = 0; j < 8; j++) {
let n = 1 + (i * 8 + j);
if ((i + j) % 2) {
tab.innerHTML += '<div class="grid-item black">'+n+'</div>'
} else {
tab.innerHTML += '<div class="grid-item white">'+n+'</div>'
}
}
}
.grid-container {
display: grid;
grid-template-columns: repeat(8, 50px);
grid-template-rows: repeat(8, 50px);
background-color: #2196F3;
}
.grid-item {
background-color: rgba(255, 255, 255, 0.8);
border: 1px solid rgba(0, 0, 0, 0.8);
font-size: 30px;
text-align: center;
}
.black{
background-color: black;
}
.white {
background-color: white;
}
<div class="grid-container"></div>
Upvotes: 1