I'm trying to create a "grid" using nested for loops. When I inspect the elements in browser they are receiving the styles i'm giving them, yet they aren't actually being positioned. Even when I go in and manually change the css in browser after the JS has loaded they wont change position.
Also, would this be better solved if i used css grid instead?
var nodeList = document.querySelectorAll('.square');
const nodeArray = [].slice.call(nodeList);
for (let i = 0; i < 3; i++){
for (let j = counter; j < (counter + 3); j++){
nodeArray[j].style.right = leftPos.toString() + "%";
nodeArray[j].style.top = topPos.toString() + "%";
nodeArray[j].style.background = 'red';
nodeArray[j].style.width = '30%';
nodeArray[j].style.height = '30%';
leftPos += 33;
}
counter += 3;
leftPos = 0;
topPos += 33;
}
}
/*there are 9 div's with class square*/
Maybe you just forget to set .square{ position: absolute; } on the CSS,
With the complete HTML, CSS and JavaScript we can help.
const
nodeList = document.querySelectorAll('.square')
let
counter = 0,
leftPos = 0,
topPos = 0
for (let i = 0; i < 3; i++){
nodeList.forEach(e =>{
e.style.right = `${leftPos}%`
e.style.top = `${topPos}%`
e.style.background = 'red'
e.style.width = '30%'
e.style.height = '30%'
leftPos += 33
})
counter += 3
leftPos = 0
topPos += 33
}
.square{
position: absolute;
color: #fff;
}
<div class="square">Foo</div>
<div class="square">Bar</div>
<div class="square">Foo</div>
<div class="square">Bar</div>
<div class="square">Foo</div>
<div class="square">Bar</div>
<div class="square">Foo</div>
You can use forEach instead create another array const nodeArray = [].slice.call(nodeList);
Related
I am working on a basic sorting visualizer with using only HTML, CSS, and JS, and I've run into a problem with the animation aspect. To initialize the array, I generate random numbers within some specified range and push them on to the array. Then based on the webpage dimensions, I create divs for each element and give each one height and width dimensions accordingly, and append each to my "bar-container" div currently in the dom.
function renderVisualizer() {
var barContainer = document.getElementById("bar-container");
//Empties bar-container div
while (barContainer.hasChildNodes()) {
barContainer.removeChild(barContainer.lastChild);
}
var heightMult = barContainer.offsetHeight / max_element;
var temp = barContainer.offsetWidth / array.length;
var barWidth = temp * 0.9;
var margin = temp * 0.05;
//Creating array element bars
for (var i = 0; i < array.length; i++) {
var arrayBar = document.createElement("div");
arrayBar.className = "array-bar"
if (barWidth > 30)
arrayBar.textContent = array[i];
//Style
arrayBar.style.textAlign = "center";
arrayBar.style.height = array[i] * heightMult + "px";
arrayBar.style.width = barWidth;
arrayBar.style.margin = margin;
barContainer.appendChild(arrayBar);
}
}
I wrote the following animated selection sort and it works well, but the only "animated" portion is in the outer for-loop, and I am not highlighting bars as I traverse through them.
function selectionSortAnimated() {
var barContainer = document.getElementById("bar-container");
var barArr = barContainer.childNodes;
for (let i = 0; i < barArr.length - 1; i++) {
let min_idx = i;
let minNum = parseInt(barArr[i].textContent);
for (let j = i + 1; j < barArr.length; j++) {
let jNum = parseInt(barArr[j].textContent, 10);
if (jNum < minNum) {
min_idx = j;
minNum = jNum;
}
}
//setTimeout(() => {
barContainer.insertBefore(barArr[i], barArr[min_idx])
barContainer.insertBefore(barArr[min_idx], barArr[i]);
//}, i * 500);
}
}
I am trying to use nested setTimeout calls to highlight each bar as I traverse through it, then swap the bars, but I'm running into an issue. I'm using idxContainer object to store my minimum index, but after each run of innerLoopHelper, it ends up being equal to i and thus there is no swap. I have been stuck here for a few hours and am utterly confused.
function selectionSortTest() {
var barContainer = document.getElementById("bar-container");
var barArr = barContainer.childNodes;
outerLoopHelper(0, barArr, barContainer);
console.log(array);
}
function outerLoopHelper(i, barArr, barContainer) {
if (i < array.length - 1) {
setTimeout(() => {
var idxContainer = {
idx: i
};
innerLoopHelper(i + 1, idxContainer, barArr);
console.log(idxContainer);
let minIdx = idxContainer.idx;
let temp = array[minIdx];
array[minIdx] = array[i];
array[i] = temp;
barContainer.insertBefore(barArr[i], barArr[minIdx])
barContainer.insertBefore(barArr[minIdx], barArr[i]);
//console.log("Swapping indices: " + i + " and " + minIdx);
outerLoopHelper(++i, barArr, barContainer);
}, 100);
}
}
function innerLoopHelper(j, idxContainer, barArr) {
if (j < array.length) {
setTimeout(() => {
if (j - 1 >= 0)
barArr[j - 1].style.backgroundColor = "gray";
barArr[j].style.backgroundColor = "red";
if (array[j] < array[idxContainer.idx])
idxContainer.idx = j;
innerLoopHelper(++j, idxContainer, barArr);
}, 100);
}
}
I know this is a long post, but I just wanted to be as specific as possible. Thank you so much for reading, and any guidance will be appreciated!
Convert your sorting function to a generator function*, this way, you can yield it the time you update your rendering:
const sorter = selectionSortAnimated();
const array = Array.from( { length: 100 }, ()=> Math.round(Math.random()*50));
const max_element = 50;
renderVisualizer();
anim();
// The animation loop
// simply calls itself until our generator function is done
function anim() {
if( !sorter.next().done ) {
// schedules callback to before the next screen refresh
// usually 60FPS, it may vary from one monitor to an other
requestAnimationFrame( anim );
// you could also very well use setTimeout( anim, t );
}
}
// Converted to a generator function
function* selectionSortAnimated() {
const barContainer = document.getElementById("bar-container");
const barArr = barContainer.children;
for (let i = 0; i < barArr.length - 1; i++) {
let min_idx = i;
let minNum = parseInt(barArr[i].textContent);
for (let j = i + 1; j < barArr.length; j++) {
let jNum = parseInt(barArr[j].textContent, 10);
if (jNum < minNum) {
barArr[min_idx].classList.remove( 'selected' );
min_idx = j;
minNum = jNum;
barArr[min_idx].classList.add( 'selected' );
}
// highlight
barArr[j].classList.add( 'checking' );
yield; // tell the outer world we are paused
// once we start again
barArr[j].classList.remove( 'checking' );
}
barArr[min_idx].classList.remove( 'selected' );
barContainer.insertBefore(barArr[i], barArr[min_idx])
barContainer.insertBefore(barArr[min_idx], barArr[i]);
// pause here too?
yield;
}
}
// same as OP
function renderVisualizer() {
const barContainer = document.getElementById("bar-container");
//Empties bar-container div
while (barContainer.hasChildNodes()) {
barContainer.removeChild(barContainer.lastChild);
}
var heightMult = barContainer.offsetHeight / max_element;
var temp = barContainer.offsetWidth / array.length;
var barWidth = temp * 0.9;
var margin = temp * 0.05;
//Creating array element bars
for (var i = 0; i < array.length; i++) {
var arrayBar = document.createElement("div");
arrayBar.className = "array-bar"
if (barWidth > 30)
arrayBar.textContent = array[i];
//Style
arrayBar.style.textAlign = "center";
arrayBar.style.height = array[i] * heightMult + "px";
arrayBar.style.width = barWidth;
arrayBar.style.margin = margin;
barContainer.appendChild(arrayBar);
}
}
#bar-container {
height: 250px;
white-space: nowrap;
width: 3500px;
}
.array-bar {
border: 1px solid;
width: 30px;
display: inline-block;
background-color: #00000022;
}
.checking {
background-color: green;
}
.selected, .checking.selected {
background-color: red;
}
<div id="bar-container"></div>
So I thought about this, and it's a little tricky, what I would do is just store the indexes of each swap as you do the sort, and then do all of the animation seperately, something like this:
// how many elements we want to sort
const SIZE = 24;
// helper function to get a random number
function getRandomInt() {
return Math.floor(Math.random() * Math.floor(100));
}
// this will hold all of the swaps of the sort.
let steps = [];
// the data we are going to sort
let data = new Array(SIZE).fill(null).map(getRandomInt);
// and a copy that we'll use for animating, this will simplify
// things since we can just run the sort to get the steps and
// not have to worry about timing yet.
let copy = [...data];
let selectionSort = (arr) => {
let len = arr.length;
for (let i = 0; i < len; i++) {
let min = i;
for (let j = i + 1; j < len; j++) {
if (arr[min] > arr[j]) {
min = j;
}
}
if (min !== i) {
let tmp = arr[i];
// save the indexes to swap
steps.push({i1: i, i2: min});
arr[i] = arr[min];
arr[min] = tmp;
}
}
return arr;
}
// sort the data
selectionSort(data);
const container = document.getElementById('container');
let render = (data) => {
// initial render...
data.forEach((el, index) => {
const div = document.createElement('div');
div.classList.add('item');
div.id=`i${index}`;
div.style.left = `${2 + (index * 4)}%`;
div.style.top = `${(98 - (el * .8))}%`
div.style.height = `${el * .8}%`
container.appendChild(div);
});
}
render(copy);
let el1, el2;
const interval = setInterval(() => {
// get the next step
const {i1, i2} = steps.shift();
if (el1) el1.classList.remove('active');
if (el2) el2.classList.remove('active');
el1 = document.getElementById(`i${i1}`);
el2 = document.getElementById(`i${i2}`);
el1.classList.add('active');
el2.classList.add('active');
[el1.id, el2.id] = [el2.id, el1.id];
[el1.style.left, el2.style.left] = [el2.style.left, el1.style.left]
if (!steps.length) {
clearInterval(interval);
document.querySelectorAll('.item').forEach((el) => el.classList.add('active'));
}
}, 1000);
#container {
border: solid 1px black;
box-sizing: border-box;
padding: 20px;
height: 200px;
width: 100%;
background: #EEE;
position: relative;
}
#container .item {
position: absolute;
display: inline-block;
padding: 0;
margin: 0;
width: 3%;
height: 80%;
background: #cafdac;
border: solid 1px black;
transition: 1s;
}
#container .item.active {
background: green;
}
<div id="container"></div>
I have some articles on the block. Some of them cut in the middle of their hight like on the picture:
I tried to fix this problem by using the function below, but it still doesn't work.
const setSameHeightToAll = function() {
const all = document.querySelectorAll('.text_blog')
let maxHeight = 0
var length = all.length
for (var i = 0; i < length; i++) {
if (all[i].getBoundingClientRect().height > maxHeight) {
maxHeight = all[i].getBoundingClientRect().height
}
}
for (var j = 0; j < length; j++) {
all[j].setAttribute('style', 'height:' + maxHeight + 'px')
}
}
in html:(this is pug.js)
.text_blog
!= post.content.full
p.read_more
a(href='/blog/'+post.key) leia mais >>
this is css:
.text_blog {
overflow: hidden;
height: 112px;
}
How can I change my function to work correctly.
You're setting the max-height to 0 in your javascript code.
Not knowing the full context of your code, because you only posted the javascript part, You may either have a constant height for all '.text_blog' elements or use
CSS
.text_blog{
height: auto;
overflow: scroll;
}
OR
JAVASCRIPT
const setSameHeightToAll = function() {
const all = document.querySelectorAll('.text_blog')
//GET HEIGHT OF FIRST ELEMENT AND MAKE IT UNIFORM
let maxHeight = all.firstElementChild.offsetHeight;
//SET CONSTANT HEIGHT
let maxHeight = '500px';
var length = all.length;
for (var i = 0; i < length; i++) {
all[i].setAttribute('style', 'height:' + maxHeight + 'px')
}
}
You are also forgetting to include the closing ';' at the end of some lines.
I'm trying to practice my scripting by making a Battleship game. As seen here.
I'm currently trying to make the board 2D. I was able to make a for-loop in order to make the board, however, due to testing purposes, I'm just trying to make the board, upon clicking a square, it turns red... But, the bottom square always lights up. I tried to debug it by making the c value null, but then it just stops working. I know it's not saving the c value properly, but I'm wondering how to fix this.
Do I have to make 100 squares by my self or can I actually have the script do it?
maincansize = 400;
document.getElementById("Main-Canvas").style.height = maincansize;
document.getElementById("Main-Canvas").style.width = maincansize;
document.getElementById("Main-Canvas").style.position = "relative";
var ize = maincansize * .1;
for (var a = 0; a < 10; a++) {
for (var b = 0; b < 10; b++) {
var c = document.createElement("div");
var d = c;
c.onclick = function() {
myFunction()
};
function myFunction() {
console.log("A square was clicked..." + c.style.top); d.style.backgroundColor = "red";
}
c.style.height = ize;
c.style.width = ize;
c.style.left = b * ize;
c.style.top = a * ize;
c.style.borderColor = "green";
c.style.borderStyle = "outset";
c.style.position = "absolute";
console.log(ize);
document.getElementById('Main-Canvas').appendChild(c);
} //document.getElementById('Main-Canvas').innerHTML+="<br>";
}
#Main-Canvas {
background-color: #DDDDDD;
}
<div>
<div id="header"></div>
<script src="HeaderScript.js"></script>
</div>
<div id="Main-Canvas" style="height:400;width:400;">
</div>
Here's your code with some fixes:
adding 'px' to style assignment
passing the clicked element to myFunction
var maincansize = 400;
document.getElementById("Main-Canvas").style.height = maincansize;
document.getElementById("Main-Canvas").style.width = maincansize;
document.getElementById("Main-Canvas").style.position = "relative";
var ize = maincansize * .1;
for (var a = 0; a < 10; a++) {
for (var b = 0; b < 10; b++) {
var c = document.createElement("div");
c.onclick = function(ev) {
myFunction(ev.currentTarget);
};
function myFunction(el) {
console.log("A square was clicked...");
el.style.backgroundColor = "red";
}
c.style.height = ize+'px';
c.style.width = ize+'px';
c.style.left = (b * ize)+'px';
c.style.top = (a * ize)+'px';
c.style.borderColor = "green";
c.style.borderStyle = "outset";
c.style.position = "absolute";
document.getElementById('Main-Canvas').appendChild(c);
}
}
#Main-Canvas {
background-color: #DDDDDD;
}
<div id="Main-Canvas" style="height:400;width:400;">
</div>
Here's a solution with major revamps. Since you're using a set width for the container element of your board cells you can float the cells and they will wrap to the next line. Absolute positioning tends to be a bit of a bugger. If you want 10 items per row it's as easy as:
<container width> / <items per row> = <width>
Using document fragments is faster than appending each individual element one at a time to the actual DOM. Instead you append the elements to a document fragment that isn't a part of the DOM until you append it. This way you're doing a single insert for all the cells instead of 100.
I moved some of the styling to CSS, but could easily be moved back to JS if you really need to.
function onCellClick() {
this.style.backgroundColor = 'red';
console.log( 'selected' );
}
var main = document.getElementById( 'board' ),
frag = document.createDocumentFragment(),
i = 0,
len = 100;
for ( ; i < len; i++ ) {
div = document.createElement( 'div' );
div.addEventListener( 'click', onCellClick, false );
frag.appendChild( div );
}
main.appendChild( frag );
#board {
width: 500px;
height: 500px;
}
#board div {
float: left;
box-sizing: border-box;
width: 50px;
height: 50px;
border: 1px solid #ccc;
}
<div id="board"></div>
Sorry for the long question.
I have tried to create a meetings on a calendar for a day. I need help to take care of the overlapping intervals.
The code I have written in following :
HTML
<body>
<div id="timeline"></div>
<div id="calendar" class="calendar">
</div>
</body>
CSS
.calendar {
border: 1px solid black;
position: absolute;
width: 600px;
height: 1440px;
left: 60px;
}
.event {
position: absolute;
float: left;
width: 100%;
overflow: auto;
border: 0px solid red;
}
#timeline {
position: absolute;
float: left;
}
JS
function getRandomColor() {
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
function creatTimeline(tl) {
var i = 0;
while (i < tl.length) {
var divEl = document.createElement('div');
divEl.style.width = '50px';
divEl.style.height = '120px';
divEl.style.border = '0px solid yellow';
divEl.innerHTML = tl[i];
var timeLine = document.getElementById('timeline');
timeLine.appendChild(divEl);
i++;
}
}
function appendEventDivs(eventArr) {
var i = 0;
while (i < eventArr.length) {
var eventEl = document.createElement('div');
eventEl.className = 'event';
eventEl.style.height = eventArr[i].height;
eventEl.style.top = eventArr[i].top;
eventEl.style.background = eventArr[i].color;
eventEl.style.width = eventArr[i].width;
eventEl.style.left = eventArr[i].left;
eventEl.innerHTML = 'Meeting' + eventArr[i].id;
var cl = document.getElementById('calendar');
cl.appendChild(eventEl);
i++;
}
}
function collidesWith(a, b) {
return a.end > b.start && a.start < b.end;
}
function checkCollision(eventArr) {
for (var i = 0; i < eventArr.length; i++) {
eventArr[i].cols = [];
for (var j = 0; j < eventArr.length; j++) {
if (collidesWith(eventArr[i], eventArr[j])) {
eventArr[i].cols.push(i);
}
}
}
return eventArr;
}
function updateEvents(eventArr) {
eventArr = checkCollision(eventArr);
var arr = [];
arr = eventArr.map(function(el) {
//just to differentiate each event with different colours
el.color = getRandomColor();
el.height = (el.end - el.start) * 2 + 'px';
el.top = (el.start) * 2 + 'px';
el.width = (600 / el.cols.length) + 'px';
return el;
});
return arr;
}
var events = [{
id: 123,
start: 60,
end: 150
}, {
id: 124,
start: 540,
end: 570
}, {
id: 125,
start: 555,
end: 600
}, {
id: 126,
start: 585,
end: 660
}];
var timeline = ['9AM', '10AM', '11AM', '12Noon', '1PM', '2PM', '3PM', '4PM', '5PM', '6PM', '7PM', '8PM', '9PM'];
function getEvents (eventArr) {
eventArr.sort(function(a, b) {
return a.start - b.start;
});
eventArr = updateEvents(eventArr);
appendEventDivs(eventArr);
console.log(eventArr);
//PART 1 - function returning the eventArr with all the required attributes
return eventArr;
};
creatTimeline(timeline);
getEvents(events);
Working fiddle here
Can anybody guide me how to take care of the overlapping intervals so that they appear side-by-side and not on top of each other.
Thanks in advance.
You need to figure out in which column each of the events should be before you can determine their width or left-position. To do this, you need to also store which of the colliding events came before each event:
function checkCollision(eventArr) {
for (var i = 0; i < eventArr.length; i++) {
eventArr[i].cols = [];
eventArr[i].colsBefore=[];
for (var j = 0; j < eventArr.length; j++) {
if (collidesWith(eventArr[i], eventArr[j])) {
eventArr[i].cols.push(j);
if(i>j) eventArr[i].colsBefore.push(j); //also list which of the conflicts came before
}
}
}
return eventArr;
}
Now, we can figure out the column of each event. Once we've done that, we can figure out how wide they should be, and with that, the horizontal positioning should be easy. This should be done inside your updateEvents function. I've got more detailed explanation commented in the comments of the code below.
function updateEvents(eventArr) {
eventArr = checkCollision(eventArr);
var arr=eventArr.slice(0); //clone the array
for(var i=0; i<arr.length; i++){
var el=arr[i];
el.color = getRandomColor();
el.height = (el.end - el.start) * 2 + 'px';
el.top = (el.start) * 2 + 'px';
if(i>0 && el.colsBefore.length>0){ //check column if not the first event and the event has collisions with prior events
if(arr[i-1].column>0){ //if previous event wasn't in the first column, there may be space to the left of it
for(var j=0;j<arr[i-1].column;j++){ //look through all the columns to the left of the previous event
if(el.colsBefore.indexOf(i-(j+2))===-1){ //the current event doesn't collide with the event being checked...
el.column=arr[i-(j+2)].column; //...and can be put in the same column as it
}
}
if(typeof el.column==='undefined') el.column=arr[i-1].column+1; //if there wasn't any free space, but it ito the right of the previous event
}else{
var column=0;
for(var j=0;j<el.colsBefore.length;j++){ //go through each column to see where's space...
if(arr[el.colsBefore[el.colsBefore.length-1-j]].column==column) column++;
}
el.column=column;
}
}else el.column=0;
}
//We need the column for every event before we can determine the appropriate width and left-position, so this is in a different for-loop:
for(var i=0; i<arr.length; i++){
arr[i].totalColumns=0;
if(arr[i].cols.length>1){ //if event collides
var conflictGroup=[]; //store here each column in the current event group
var conflictingColumns=[]; //and here the column of each of the events in the group
addConflictsToGroup(arr[i]);
function addConflictsToGroup(a){
for(k=0;k<a.cols.length;k++){
if(conflictGroup.indexOf(a.cols[k])===-1){ //don't add same event twice to avoid infinite loop
conflictGroup.push(a.cols[k]);
conflictingColumns.push(arr[a.cols[k]].column);
addConflictsToGroup(arr[a.cols[k]]); //check also the events this event conflicts with
}
}
}
arr[i].totalColumns=Math.max.apply(null, conflictingColumns); //set the greatest value as number of columns
}
arr[i].width=(600/(arr[i].totalColumns+1))+'px';
arr[i].left=(600/(arr[i].totalColumns+1)*arr[i].column)+'px';
}
return arr;
}
Working Fiddle: https://jsfiddle.net/ilpo/ftbjan06/5/
I added a few other events to test different scenarios.
Oh, and by the way, absolutely positioned elements can't float.
You already know the top and height of every event, so you could map the calendar and check an event already exist within the area it will occupy, then offset the left value by the number of existing events.
I'm trying to make the first row of a chess board. I had it but Im trying to make what I think what's called a constructor function to learn more advanced programming. I'm trying to get all the data in the function and append the div to the board the x should be updated by multiplying i * the piece size.I think I'm having problems using the new key word and appending together. If you could show me how you would fill up the whole chess board that would be great. I'm assuming you would use nested for loops. That's my next goal.
I have something like this.
$(function(){
var boardHeight = parseInt($(".board").css("height")),
boardWidth = parseInt($(".board").css("width")),
amountOfPieces =8,
pieceSize = boardHeight / amountOfPieces,
board = $(".board");
console.log(pieceSize);
function Cell(orange, x){
this.width = pieceSize;
this.height = pieceSize;
this.color = orange ? "orange" : "black"
this.x = x;
}
console.log( new Cell())
for(var i = 0 ; i < amountOfPieces; i++){
if(i % 2 == 0){
board.append($("<div>") new cell("orange", i * pieceSize))
}else if( i % 2 == 1){
board.append($("<div>").css({
position: "absolute",
width : pieceSize,
height: pieceSize,
"background-color" : "black",
left: i * pieceSize
}))
}
}
});
EDIT: ok guys I got the first row shown in my answer. now I need to fill in the whole board. Remember the colors need to alternate and I would prefer to use a nested for loop. Thanks.
You should be passing pieceSize in as an argument like:
function Cell(orange, x, size) {
this.width = size;
this.height = size;
this.color = orange ? "orange" : "black"
this.x = x; // What is x used for anyway?
}
Then when you use it, it would look something like (just an example):
var createdCell = new Cell(true, 0, pieceSize);
Also the following line is all messed up on multiple levels:
board.append($("<div>") new cell("orange", i * pieceSize))
Take a look at the jQuery .append() documentation to get a better understanding of how to use it: http://api.jquery.com/append/
All your Cell constructor function does is create objects with the parameters of one space on the game board. It doesn't actually build it. You'll need to create a function that takes in the object produced by new Cell() an actually creates a string of HTML for you to append to the page. Something like:
function create(cell) {
var str = '<div class="whatever" style="';
str+= 'height: ' + cell.height + ';';
str+= 'width: ' + cell.width + ';';
str+= 'background: ' + cell.color + ';';
'">';
str += '</div>';
return str;
}
Then you could do something like:
board.append(create(new Cell(true, 0, pieceSize)))
This answer is not something for you to copy/paste into your project. These are examples to give you the tools you'll need to solve this problem.
Ok I came up with this answer. what do you think?
$(function(){
var boardHeight = parseInt($(".board").css("height")),
boardWidth = parseInt($(".board").css("width")),
amountOfPieces =8,
pieceSize = boardHeight / amountOfPieces,
board = $(".board");
console.log(pieceSize);
function Cell(orange, x){
this.width = pieceSize;
this.height = pieceSize;
this.background = orange ? "orange" : "black"
this.left = x;
this.position = "absolute"
}
console.log( new Cell())
for(var i = 0 ; i < amountOfPieces; i++){
if(i % 2 == 0){
var obj = new Cell("orange", i * pieceSize)
console.log(obj)
board.append($("<div>").css(obj))
}else if( i % 2 == 1){
var obj = new Cell("",i * pieceSize )
board.append($("<div>").css(obj))
}
}
})
.board{
background: #ccc;
width: 500px;
height: 500px;
margin: 20px auto;
position: relative;
}
.cell{
position: absolute;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<div class="board"></div>
Now on to making the columns. any help with that guys?
EDIT: I came up with an answer to fill the whole board and it is below. I still would like to see other people's results
$(function(){
var boardHeight = parseInt($(".board").css("height")),
boardWidth = parseInt($(".board").css("width")),
amountOfPieces =8,
pieceSize = boardHeight / amountOfPieces,
board = $(".board");
console.log(pieceSize);
function Cell(orange, x, y){
this.width = pieceSize;
this.height = pieceSize;
this.background = orange ? "orange" : "black"
this.left = x;
this.position = "absolute"
this.top = y
}
console.log( new Cell())
for(var i = 0; i < amountOfPieces ; i ++){
for(var j = 0 ; j < amountOfPieces; j++){
if(i % 2 == 0){
if(j % 2 == 1){
var obj = new Cell("orange", i * pieceSize , j * pieceSize)
console.log(obj)
board.append($("<div>").css(obj))
}else{
var obj = new Cell("", i * pieceSize , j * pieceSize)
console.log(obj)
board.append($("<div>").css(obj))
}
}else if( i % 2 == 1){
if(j % 2 == 1){
var obj = new Cell("", i * pieceSize , j * pieceSize)
board.append($("<div>").css(obj))
}else{
var obj = new Cell("orange", i * pieceSize , j * pieceSize)
board.append($("<div>").css(obj))
}
}
}
}
})
.board{
background: #ccc;
width: 500px;
height: 500px;
margin: 20px auto;
position: relative;
}
.cell{
position: absolute;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<div class="board"></div>
Try using .slice(), .filter(), :odd, :even, .addBack(), Array.prototype.reverse()
for (var i = n = 0, colors = ["orange", "black"]; i < 64; i++, n = i % 8 + 1) {
$("<div class=row>").appendTo("section");
if (n === 8) {
$(".row").slice(i === n - 1 ? 0 : $(".row").length - n, i + 1)
.filter(":even").css("background", colors[0])
.addBack().filter(":odd").css("background", colors[1]);
colors.reverse(); $("section").append("<br>");
}
}
div {
position: relative;
width: 65px;
height: 65px;
display: inline-block;
padding: 0;
margin-left: 2px;
margin-right: 2px;
outline: 2px solid brown;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<section>
</section>