I am trying to make a chessboard using javascript and creating 64 divs with it.
The problem is, that it creates only the first div.
Here is the code:
div {
width: 50px;
height: 50px;
display: block;
position: relative;
float: left;
}
<script type="text/javascript">
window.onload=function()
{
var i=0;
var j=0;
var d=document.createElement("div");
for (i=1; i<=8; i++)
{
for (j=1; j<=8; j++)
{
if ((i%2!=0 && j%2==0)||(i%2==0 && j%2!=0))
{
document.body.appendChild(d);
d.className="black";
}
else
{
document.body.appendChild(d);
d.className="white";
}
}
}
}
</script>
As t-j-crowder has noted, the OP's code only creates one div. But, for googlers, there is one way to append multiple elements with a single appendChild in the DOM: by creating a documentFragment.
function createDiv(text) {
var div = document.createElement("div");
div.appendChild(document.createTextNode(text));
return div;
}
var divs = [
createDiv("foo"),
createDiv("bar"),
createDiv("baz")
];
var docFrag = document.createDocumentFragment();
for(var i = 0; i < divs.length; i++) {
docFrag.appendChild(divs[i]); // Note that this does NOT go to the DOM
}
document.body.appendChild(docFrag); // Appends all divs at once
The problem is, that it creates only the first div.
Right, because you've only created one div. If you want to create more than one, you must call createElement more than once. Move your
d=document.createElement("div");
line into the j loop.
If you call appendChild passing in an element that's already in the DOM, it's moved, not copied.
window.onload=function()
{
var i=0;
var j=0;
for (i=1; i<=8; i++)
{
for (j=1; j<=8; j++)
{
if ((i%2!=0 && j%2==0)||(i%2==0 && j%2!=0))
{
var d=document.createElement("div");
document.body.appendChild(d);
d.className="black";
}
else
{
var d=document.createElement("div");
document.body.appendChild(d);
d.className="white";
}
}
}
}
Although what T.J. Crowder writes works fine, I would recommend rewriting it to the code below, using a documentFragment, like Renato Zannon suggested. That way you will only write to the DOM once.
window.onload = function() {
var count = 5,
div,
board = document.getElementById('board'),
fragment = document.createDocumentFragment();
// rows
for (var i = 0; i < count; ++i) {
// columns
for (var j = 0; j < count; ++j) {
div = document.createElement('div');
div.className = (i % 2 != 0 && j % 2 == 0) || (i % 2 == 0 && j % 2 != 0) ? 'black' : 'white';
fragment.appendChild(div);
}
}
board.appendChild(fragment);
};
#board {
background-color: #ccc;
height: 510px;
padding: 1px;
width: 510px;
}
.black,
.white {
float: left;
height: 100px;
margin: 1px;
width: 100px;
}
.black {
background-color: #333;
}
.white {
background-color: #efefef;
}
<div id="board"></div>
function crt_dv(){
dv=document.createElement('div'),document.body.appendChild(dv)
};
crt_dv(),dv.className='white';crt_dv(),dv.className='black';
Also use: for(i=0;i<2;i++)
Related
I have a 16x16 grid of small squares. I have added a permanent "hover" effect to make the very first box turn red when I put my mouse over it. However, I want to add the same effect to all of the boxes on the page. I can't figure out how to do it - I have tried to add an event listener to the whole page and used target.nodeName and target.NodeValue, but to no avail. I have included the working version where the fix box turns red on mouseover.
var n=16; //take grid column value as you want
const bigContainer = document.querySelector('.bigContainer')
for(var i = 1; i < n; i++) {
bigContainer.innerHTML+='<div class="row">';
for(j = 0; j < n; j++) {
bigContainer.innerHTML+='<div class="smallBox">';
}
}
const smallBox = document.querySelector('.smallBox');
smallBox.addEventListener('mouseover', () => {
smallBox.classList.add('permahover');
});
.smallBox {
border: 1px solid black;
width: 20px;
height: 20px;
display: inline-block;
}
.permahover {
background: red;
}
h1 {
text-align: center;
}
.bigContainer {
text-align: center;
}
<h1>Etch-a-Sketch Assignment - The Odin Project</h1>
<div class="bigContainer">
</div>
The immediate problem you are having is that this is only querying, and subsequently adding an event listener to, one element.
const smallBox = document.querySelector('.smallBox');
smallBox.addEventListener('mouseover', () => {
smallBox.classList.add('permahover');
});
In the above portion of your code, querySelector only returns the first matching element. You may be looking for querySelectorAll here which returns a NodeList of matching elements.
You have two options (perhaps others if you want to restructure your code further). The naive approach is to, in fact, query for all of the cells and add event listeners to each of them.
var n=16; //take grid column value as you want
const bigContainer = document.querySelector('.bigContainer')
for(var i = 1; i < n; i++) {
bigContainer.innerHTML+='<div class="row">';
for(j = 0; j < n; j++) {
bigContainer.innerHTML+='<div class="smallBox">';
}
}
const smallBoxes = document.querySelectorAll('.smallBox');
[...smallBoxes].forEach(smallBox => {
smallBox.addEventListener('mouseover', () => {
smallBox.classList.add('permahover');
});
})
.smallBox {
border: 1px solid black;
width: 20px;
height: 20px;
display: inline-block;
}
.permahover {
background: red;
}
h1 {
text-align: center;
}
.bigContainer {
text-align: center;
}
<h1>Etch-a-Sketch Assignment - The Odin Project</h1>
<div class="bigContainer">
</div>
Another option is to use event delegation as you identified. Here is how you can leverage that. Note: this approach is a bit tricker for an aggressive event like "mouseover" as you may get false positive targets (like the outer container for example).
var n=16; //take grid column value as you want
const bigContainer = document.querySelector('.bigContainer')
for(var i = 1; i < n; i++) {
bigContainer.innerHTML+='<div class="row">';
for(j = 0; j < n; j++) {
bigContainer.innerHTML+='<div class="smallBox">';
}
}
bigContainer.addEventListener('mouseover', e => {
var target = e.target
if (target !== bigContainer) {
target.classList.add('permahover')
}
})
.smallBox {
border: 1px solid black;
width: 20px;
height: 20px;
display: inline-block;
}
.permahover {
background: red;
}
h1 {
text-align: center;
}
.bigContainer {
text-align: center;
}
<h1>Etch-a-Sketch Assignment - The Odin Project</h1>
<div class="bigContainer">
</div>
You need to use a delegation event, because all the small boxes don't exist on the page when the page is loaded (You can figure out in the inspector element that only your first box has the event listener).
So you listen the whole container (because it is always on the page on load)
bigContainer.addEventListener('mouseover', () => {
// Code for checking if we hovered a small div & if yes applying the style
});
...and then do a comparaison with the event.target (which will be the small div hovered)
if (event.target.matches('.smallBox')) {
event.target.classList.add('permahover');
}
var n=16; //take grid column value as you want
const bigContainer = document.querySelector('.bigContainer')
for(var i = 1; i < n; i++) {
bigContainer.innerHTML+='<div class="row">';
for(j = 0; j < n; j++) {
bigContainer.innerHTML+='<div class="smallBox">';
}
}
const smallBox = document.querySelector('.smallBox');
bigContainer.addEventListener('mouseover', () => {
if (event.target.matches('.smallBox')) {
event.target.classList.add('permahover');
}
});
.smallBox {
border: 1px solid black;
width: 20px;
height: 20px;
display: inline-block;
}
.permahover {
background: red;
}
h1 {
text-align: center;
}
.bigContainer {
text-align: center;
}
<h1>Etch-a-Sketch Assignment - The Odin Project</h1>
<div class="bigContainer">
</div>
You can use forEach method to loop through all boxes and add eventListener on each one.
If all of them have .smallBox class you can do it like this:
const smallBoxes = document.querySelectorAll('.smallBox');
smallBoxes.forEach(box => box.addEventListener('mouseover', () => {
smallBox.classList.add('permahover');
}))
I hope it helped you!
let smallBoxes = document.querySelectorAll('.smallBox');
[...smallBoxes].forEach(el => {
el.addEventListener('mouseover', e => e.target.classList.add('permahover'));
});
you should set the eventlistener to your DOM and ask if the trigger element are one of your elements which are that specific class. So you can handle every element with that class.
var n = 16; //take grid column value as you want
const bigContainer = document.querySelector('.bigContainer')
for (var i = 1; i < n; i++) {
bigContainer.innerHTML += '<div class="row">';
for (j = 0; j < n; j++) {
bigContainer.innerHTML += '<div class="smallBox">';
}
}
document.addEventListener('mouseover', function(e) {
if (e.target && e.target.className == 'smallBox') {
var target = e.target;
target.classList.add('permahover');
}
});
Working js fiddle: https://jsfiddle.net/nwukf205/
hope i could help you :)
if you got questions just ask
Have you tried the :hover selector? Not sure if you want specify any dynamic actions here, but it's easy to do basic stuff.
https://www.w3schools.com/cssref/sel_hover.asp
a:hover {
background-color: yellow;
}
I haven't tried your example myself but something similar to this has been answered here:
Hover on element and highlight all elements with the same class
I recently started learning how to use JavaScript in my webpage. My exercise today is to make a button that can give me a V shape.
The code to create the V shape is fine, but it doesn't work when I try to put it in a click handler (i.e. oBtn.click = function (){};).
In the HTML document I have the following code:
<style>
div{
width: 50px;
height: 50px;
border: 1px red solid;
position: absolute;
line-height: 50px;
text-align: center;
margin: 5px;
}
</style>
<script type="text/javascript">
window.onload = function (){
var oBody = document.getElementById('body');
var aDiv = document.getElementsByTagName('div');
var oBtn1 = document.getElementById('btn1');
for (var i = 0; i < 9; i++) {
oBody.innerHTML += '<div>'+ i +'</div>';
}
for (var i = 0; i < aDiv.length; i++) {
aDiv[i].style.left =i*50+'px';
}
oBtn1.onclick = function (){
for (var i = 0; i < aDiv.length/2; i++) {
aDiv[i].style.top = 40+i*50+'px';
}
var x = aDiv.length;
for (var i = 4; i < x; i++) {
aDiv[i].style.top =x*50-i*50-50+40+'px';
}
};
};
</script>
I believe this is close to what you wanted. Runs in chrome, but may not in other browsers (notably IE). Doesn't work as a snippet, sorry. I suspect trying to modify all divs in the body is going to cause you trouble in the long term. A couple of things to notice:
You don't need to get the body by name, you can just use document.body (I'm making an assumption here - however giving an element the id "body" could easily cause confusion)
Your divs must be created before you try to get the array from the DOM
Event handlers are done using the commonly preferred method.
<html>
<head>
<style>
div{
width: 50px;
height: 50px;
border: 1px red solid;
position: absolute;
line-height: 50px;
text-align: center;
margin: 5px;
}
</style><script>
window.addEventListener("DOMContentLoaded", function () {
for (var i = 0; i < 9; i++) {
document.body.innerHTML += '<div>'+ i +'</div>';
}
var aDiv = document.getElementsByTagName('div');
for (var i = 0; i < aDiv.length; i++) {
aDiv[i].style.left =i*50+'px';
}
document.getElementById('btn1').addEventListener("click", function () {
for (var i = 0; i < aDiv.length/2; i++) {
aDiv[i].style.top = 40+i*50+'px';
}
var x = aDiv.length;
for (var i = 4; i < x; i++) {
aDiv[i].style.top =x*50-i*50-50+40+'px';
}
});
}, false);
</script>
</head>
<body>
<input type="button" id="btn1"><br />
</body>
</html>
If I understand this right, you want to execute 'oBtn1.onclick' as a click event? If so, do something like this
function buttonClick (){
for (var i = 0; i < aDiv.length/2; i++) {
aDiv[i].style.top = 40+i*50+'px';
}
oBtn1.addEventListener('click', buttonClick);
what that will do is as soon as the element that contains the id 'oBtn1' is clicked it will execute your for loop.
What does your html look like? If it looks kind of like the below snippet then it should be working, though you should look at using addEventListener for this kind of thing.
window.onload = function (){
var oBody = document.getElementById('body');
var aDiv = document.getElementsByTagName('div');
var oBtn1 = document.getElementById('btn1');
for (var i = 0; i < 9; i++) {
oBody.innerHTML += '<div>'+ i +'</div>';
}
for (var i = 0; i < aDiv.length; i++) {
aDiv[i].style.left =i*50+'px';
}
oBtn1.onclick = function (){
for (var i = 0; i < aDiv.length/2; i++) {
aDiv[i].style.top = 40+i*50+'px';
}
var x = aDiv.length;
for (var i = 4; i < x; i++) {
aDiv[i].style.top =x*50-i*50-50+40+'px';
}
};
};
div{
width: 50px;
height: 50px;
border: 1px red solid;
position: absolute;
line-height: 50px;
text-align: center;
margin: 5px;
}
<button id="btn1">press</button>
<div id="body"></div>
I'm working on a card game where the user has to select a card from a set of 4. If it is an Ace then they win if not then they lose. But I'm having some trouble removing the event listener of click from the set of cards after the first card has been clicked.
for(var i = 0; i < card.length; i++)
{
card[i].addEventListener("click",display);
}
function display()
{
this.setAttribute("src","CardImages/" + deck[this.id] + ".jpg");
this.setAttribute("class","highlight");
if(firstGo == 0)
{
firstGo++;
firstCard = this;
this.removeEventListener("click",display);
console.log("card" + deck[this.id]);
}
else
{
alert("You've already selected a card");
this.removeEventListener("click",display);
}
}
You are adding click events using a loop because you have multiple cards.
for(var i = 0; i < card.length; i++) {
card[i].addEventListener("click", display);
}
but you're removing the event listeners using
this.removeEventListener("click",display);
which will only remove the listener on the card you clicked. If you want to remove the listener on other cards too, you should also remove them in a loop.
function display() {
this.setAttribute("src","CardImages/" + deck[this.id] + ".jpg");
this.setAttribute("class","highlight");
if (firstGo == 0) {
firstGo++;
firstCard = this;
// this.removeEventListener("click",display);
for (var i = 0; i < card.length; i++) {
card[i].removeEventListener("click", display);
}
console.log("card" + deck[this.id]);
} else {
alert("You've already selected a card");
// this.removeEventListener("click",display);
for (var i = 0; i < card.length; i++) {
card[i].removeEventListener("click", display);
}
}
}
Here's a working demo.
var cards = document.getElementsByClassName("card");
for (var i = 0; i < cards.length; i++) {
cards[i].addEventListener("click", display);
}
function display() {
this.classList.add("highlight");
for (var i = 0; i < cards.length; i++) {
cards[i].removeEventListener("click", display);
}
}
.card {
float: left;
padding: 50px 40px;
border: 1px solid rgba(0,0,0,.2);
margin: 5px;
background: white;
}
.card:hover {
border: 1px solid rgba(0,0,255,.4);
}
.card.highlight {
border: 1px solid rgba(0,200,0,.5);
}
<div class="card">1</div>
<div class="card">2</div>
<div class="card">3</div>
<div class="card">4</div>
I'm not sure what your card array looks like, but I filled in the rest on a codepen and it seems to be successfully removing the eventListener. Is your card array referencing specific DOM elements like this for example?
var a = document.getElementById('A');
var b = document.getElementById('B');
var c = document.getElementById('C');
var card = [a, b, c];
I'm trying to update a set of divs class="oct_days" to give them id based on :nth-child(n). The format of the id is oct_n. I'm trying to accomplish this using a for loop to set this for divs.
window.onload = function addOctDate() {
var cls = document.getElementByClass("oct_days");
for (var n = 1; n < 32; n++) {
cls[n].id = "oct_" + n;
}
};
Fiddle (http://jsfiddle.net/ascottz/D9Exm/)
The idea is to have .oct_days:nth-child(1) have id="oct_1", but id isn't being set.
clsyour issues are this:
window.onload was being run before your html was initialized
you need to call document.getElementsByClassName not
you are starting your iteration at 1, indexes are 0 based and you should start there and add the + 1 as noted below
also, while iterating, its good to only iterate only over the known items in your list
try this code:
function addOctDate() {
var cls = document.getElementsByClassName("oct_days");
for (n=0, length = cls.length; n < length; n++) {
cls[n].id= "oct_" + (n + 1);
}
};
addOctDate()
The function is getElementsByClassName.
The fiddle doesn't work because you're seeing window.onload while your code is already being run inside that event (the dropdown on the left says onLoad). It'll also error out because you don't have 31 elements in the HTML, but it'll still set the IDs.
Your code is very simple to fix
(function () {
// .getElementsByClassName not .getElementByClass
var cls = document.getElementByClassName("oct_days"),
// set the stopping point DYNAMICALLY
len = cls.length,
// start the index at 0;
n = 0;
for (; n < len; n++) {
cls[n].id = "oct_" + (n + 1);
}
// ()(); auto runs the function
})();
Here is a way to add ids to elements and classes using just plain js.
HTML
<div id="test">
Content will append below!
<input type="button" value="click me!" onClick="myFunction();"/>
</div>
CSS
.cool_0 {
background: red;
height: 200px;
width: 100%;
}
.cool_1 {
background: yellow;
height: 200px;
width: 100%;
}
.cool_2 {
background: red;
height: 200px;
width: 100%;
}
.cool_3 {
background: yellow;
height: 200px;
width: 100%;
}
.cool_4 {
background: red;
height: 200px;
width: 100%;
}
.cool_5 {
background: yellow;
height: 200px;
width: 100%;
}
JS
function myFunction(){
var myId = 0;
var counter = 0;
var myDiv = document.getElementById("test")
for(var i = 0; i < 5; i++){
var textNode = document.createTextNode("sup! My current id is "+myId+" !")
var t = document.createElement("div");
t.setAttribute("id", counter++)
t.setAttribute("class", "cool_"+myId++)
t.appendChild(textNode)
myDiv.appendChild(t);
}
}
Could anyone give me a hint on how to generate a chess board (8x8) using JavaScript, using a table tags or ?
I've got the following so far:
<DOCTYPE html>
<html>
<head>
<style>
div
{
border:1px solid black;
width:20px;
height:20px;
}
</style>
</head>
<body>
<script type="text/javascript">
// create a chess table 8x8.
var count = 0;
while (count < 64)
{
if (count % 2 == 0)
{
if (count % 8 == 0 && count !=0)
{
document.write('<br/><div style="background-color:#000000;float:left;"> </div>');
}
else
{
document.write('<div style="background-color:#000000;float:left;"> </div>');
}
}
else
{
document.write('<div style="background-color:#FFFFFF;float:left;"> </div>');
}
/*
*/
count++;
}
</script>
</body>
</html>
I tried to assign black and white to each odd and even number respectively, but it doesn't work this way.
Thank you in advance.
I can not test it at this moment but this should work. This code creates a 8x8 table in which black cells are tagged with "black" class and white cells are tagged with "white" class. Use CSS to give them color. I hope it helps.
var table = document.createElement("table");
for (var i = 1; i < 9; i++) {
var tr = document.createElement('tr');
for (var j = 1; j < 9; j++) {
var td = document.createElement('td');
if (i%2 == j%2) {
td.className = "white";
} else {
td.className = "black";
}
tr.appendChild(td);
}
table.appendChild(tr);
}
document.body.appendChild(table);
At some point for me, this became code golf:
http://jsfiddle.net/4Ap4M/
JS:
for (var i=0; i< 64; i++){
document.getElementById("mainChessBoard").appendChild(document.createElement("div")).style.backgroundColor = parseInt((i / 8) + i) % 2 == 0 ? '#ababab' : 'white';
}
HTML:
<div id="mainChessBoard">
</div>
CSS:
#mainChessBoard
{
width:160px;
height:160px;
border:1px solid black;
}
div
{
width:20px;
height:20px;
float:left;
}
This is the basic foundation to build your chess board.
You can check out the chess board pattern in the console.
var chessBoard = function(size){
var hash = '#'
var space = '_'
for (var i = 0; i < size; i++)
{
hash += '\n'
for (var j = 0; j < size; j++)
{
if((i +j) % 2 == 0)
{
hash += space
}
else
{
hash += "#"
}
};
};
console.log(hash)
}(8)
You can generate boards of any size you want, and this way is pretty easy to change the size of the squares and the colors. you don't need to change anything else.
It is good practice to keep appearance on the stylesheet.
Also don't use document.write
http://jsfiddle.net/YEJ9A/1/
Javascript
var x=8;
var y=8;
var chessBoard = document.getElementById("chessBoard");
for (var i=0; i<y; i++){
var row = chessBoard.appendChild(document.createElement("div"));
for (var j=0; j<x; j++){
row.appendChild(document.createElement("span"));
}
}
CSS
#chessBoard span{
display: inline-block;
width: 32px;
height: 32px;
}
#chessBoard div:nth-child(odd) span:nth-child(even),
#chessBoard div:nth-child(even) span:nth-child(odd){
background-color: black;
}
#chessBoard div:nth-child(even) span:nth-child(even),
#chessBoard div:nth-child(odd) span:nth-child(odd){
background-color: silver;
}
May be you want to do it with divs, not with the table. So here is the solution for it.
$(document).ready(function() {
for (var i = 1; i <= 8; i++) {
var divRow = $("<div>", {
class: "row",
});
for (var j = 1; j <= 8; j++) {
var div = $("<div>", {
class: "square"
});
if (i % 2 == j % 2) {
$(div).addClass("white");
} else {
$(div).addClass("black");
}
divRow.append(div);
}
$("#board").append(divRow);
}
});
#board {
margin: 0;
width: 256px;
height: 256px;
border: solid 1px #333;
}
#board .row {
margin: 0;
}
.square {
height: 32px;
width: 32px;
background: #efefef;
float: left;
}
.square.white {
background: #fff;
}
.square.black {
background: #333;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="board"></div>
A little modernization, using css variables, css attr() and dataset attributes.
This allows to tweak themes, and keep stuffs simple.
const cols = {0:"A", 1:"B", 2:"C", 3:"D", 4:"E", 5:"F", 6:"G", 7:"H"}
const table = document.createElement("table");
table.className = "board";
for (let i = 1; i < 9; i++) {
let tr = document.createElement('tr');
tr.dataset.line = i
for (let j = 1; j < 9; j++) {
let td = document.createElement('td');
td.dataset.col = cols[j-1];
td.dataset.line = i;
td.className = (i%2 === j%2) ? "white square" : "black square";
tr.appendChild(td);
}
table.appendChild(tr);
}
document.querySelector("div").appendChild(table);
:root {
--size: 640px;
--backcolor: darkslategray;
--dark: grey;
--light: white;
--legend: azure;
--hover: lightgreen
}
.board {
width: var(--size);
height: var(--size);
border: 32px solid;
border-color: var(--backcolor);
border-radius: 0.2rem;
}
.square {
border: 1px black solid;
}
.white{
background: var(--light);
}
.black{
background: var(--dark)
}
.board tr::before {
content: attr(data-line);
position: absolute;
margin: 1.8rem 0 0rem -1.5rem;
font-size: larger;
color: var(--legend);
}
.board tr::after {
content: attr(data-line);
position: absolute;
margin: 1.8rem 0 0rem 0.8rem;
font-size: larger;
color: var(--legend);
}
.board tr:first-child > td::before {
content: attr(data-col);
position: absolute;
margin: -4rem 0 0rem 1.6rem;
font-size: larger;
color: var(--legend);
}
.board tr:last-child > td::after {
content: attr(data-col);
position: absolute;
margin: 2.6rem 0 0rem 1.6rem;
font-size: larger;
color: var(--legend);
}
td:hover {
background: var(--hover);
cursor: pointer
}
<div></div>
The following code will print chess board using only HTML and JavaScript.
<script>
document.write("<table border='1' width='200' height='200'>");
for(var i=1; i<=8; i++)
{
document.write("<tr>");
for(var j=1; j<=8; j++)
{
if((i+j)%2!=0)
{
document.write("<td bgcolor='white'></td>");
}
else
{
document.write("<td bgcolor='black'></td>");
}
}
document.write("</tr>");
}
document.write("</table>");
</script>
You should try this one this will really work
<DOCTYPE html>
<html>
<head>
<style>
.chessBoard {
display: inline-block;
border: 2px solid lightGray;
}
.chessBoard div {
line-height: 1px;
}
.chessBoard span {
display: inline-block;
width: 32px;
height: 32px;
background-color: snow;
}
</style>
</head>
<body>
<div class="chessBoard" id="chessBoardNormal"></div>
<div class="chessBoard" id="chessBoardRandom"></div>
<script>
function colorNormal(x, y, color) {
var chessBoard = document.getElementById("chessBoardNormal");
for (var i = 0; i < x; i++) {
var row = chessBoard.appendChild(document.createElement("div"));
for (var j = 0; j < y; j++) {
var span = document.createElement('span');
if (i & 1) { // odd
if (j & 1) { // white
} else { // black
span.style.backgroundColor = color;
}
} else { // even
if (j & 1) { // black
span.style.backgroundColor = color;
}
}
row.appendChild(span);
}
}
}
function colorRandom(x, y) {
colorNormal(8, 8, Math.random() > .5 ? 'black' : '#CFD65C');
}
function getRandomHexColor() {
return '#' + Math.floor(Math.random() * 16777215).toString(16);
}
colorNormal(8, 8, 'black');
</script>
</body>
</html>
My idea is simple, if row is even then start with white piece otherwise start with black piece.
HTML:
<div id="mainChessBoard"></div>
Javascript:
const fragment = document.createDocumentFragment();
const board = document.getElementById("mainChessBoard");
const size = 8;
for (let i = 0; i < size; i++) {
let start = i % 2 === 0 ? 0 : 1; // if row is even then start with white otherwise start with black;
for (let j = 0; j < size; j++) {
const div = document.createElement('div');
div.classList.add(start === 1 ? "black" : "white");
fragment.appendChild(div);
start = start === 1 ? 0 : 1;
}
}
board.appendChild(fragment);
Here's a plain JS copy-paste solution. I know it's not that clean in terms of conditioning but it does the job comprehensibly and it's quite straight forward. Field size is easily adjustable as well.
const fieldSize = 50;
const whiteField = document.createElement("div");
whiteField.style = `height:${fieldSize}px;width:${fieldSize}px;background-color:white;display:inline-block`;
const blackField = document.createElement("div");
blackField.style = `height:${fieldSize}px;width:${fieldSize}px;background-color:black;display:inline-block`;
for (let i = 0; i < 8; i++) {
for (let j = 0; j < 8; j++)
i % 2 === 0 ?
j % 2 === 0 ?
document.body.appendChild(blackField.cloneNode(true)) :
document.body.appendChild(whiteField.cloneNode(true)) :
j % 2 === 0 ?
document.body.appendChild(whiteField.cloneNode(true)) :
document.body.appendChild(blackField.cloneNode(true));
document.body.appendChild(document.createElement("br"));
}
We can always think of a better performance, here's the DOM optimized solution using documentFragments -
// main container
let container = document.querySelector("#main");
// a fragment object to store a 2-D mesh of rows and columns
let fragment = new DocumentFragment();
for (let i = 0; i < 8; i++) {
// a fragment object to store a single row with 8 columns
let rowFragment = new DocumentFragment();
for (let j = 0; j < 8; j++) {
// div element for a column
let col = document.createElement("div");
col.style.border = "1px solid";
if ((i + j) % 2 == 0) col.style.background = "black";
else col.style.background = "white";
// adding column in a document fragment
rowFragment.appendChild(col);
}
// adding row in a main fragment
fragment.appendChild(rowFragment);
}
// adding fragment to a DOM one time - this will update the DOM only once
container.appendChild(fragment);
.container {
display: flex;
width: 416px; /* width + horizontal border of each cell ((50 + 2) * 8) */
height: 416px; /* height + vertical border of each cell ((50 + 2) * 8) */
}
div {
flex-wrap: wrap; /* to fit 8 cells in a row as per the width */
width: 50px;
height: 50px;
}
<div class="container" id="main"></div>
Here, the DocumentFragment creates an object of elements we add, but it isn't a part of the active document tree unless we append it to any other DOM node.
Javascript:
var i, j, clas;
for (i = 0; i < 8; i++) {
for (j = 0; j < 8; j++) {
clas = '';
if (j === 0) clas = 'first ';
else if (j === 7) clas = 'last ';
clas += (i % 2 == j % 2) ? 'white' : 'black';
var field = document.createElement('div');
field.className = clas;
document.body.appendChild(field);
}
}
CSS:
div {
float: left;
width: 20px;
height: 20px;
}
.first {
clear: left;
}
.black {
background: black;
}
.white {
background: red;
}
Sample: http://jsfiddle.net/YJnXG/2/
You mean like this?
.... html.....
<table>
<tr>
<script language='javascript'>
<!--
alternate();
//-->
</script>
</tr>
</table>
....more html.....
function alternate()
{
var numOfCells = 6;
var num = 0;
for (i = 0; i < numOfCells ; i++)
{
txt = "<td bgColor='";
txt += (num % 2 == 0) ? 'red' : 'black';
txt += "'>"
document.write(txt);
num++;
}
}
The % sign is mod; it returns the remainder of a division. the "(...) ? ... : ...;" construction is like an if/else. If the condition is true, the first option -- else the second.