Creating a 16x16 grid using JavaScriptt bx Y

12

I'm trying to create a 16x16 grid in JavaScript. The method I'm trying to use is to create an empty div in HTML, and then append other divs to it, and outline their borders. I can't seem to make this work, and I've put my code below.

HTML:

<!DOCTYPE html>

<head>
    <title>Etch-a-Sketch</title>
    <link rel="stylesheet" type="text/css" href="style.css">
    <script type="text/javascript" src="app.js"></script>
</head>

<body>
    <div id="container">
    </div>

</body>

JavaScript:

// Sets important constants and variables

const container = document.getElementById("container");
let rows = document.getElementsByClassName("gridRow");
let cells = document.getElementsByClassName("cell");

// Creates a default grid sized 16x16
function defaultGrid() {
    makeRows(16);
    makeColumns(16);
}

// Takes (rows, columns) input and makes a grid
function makeRows(rowNum) {

    // Creates rows
    for (r = 0; r < rowNum; r++) {
        let row = document.createElement("div");
        container.appendChild(row).className = "gridRow";
    };
};

// Creates columns
function makeColumns(cellNum) {
    for (i = 0; i < rows.length; i++) {
        for (j = 0; j < cellNum; j++) {
            let newCell = document.createElement("div");
            rows[j].appendChild(newCell).className = "cell";
        };

    };
};

CSS:

.gridRow {
    border: 1px solid black;
}

.cell {
    border: 1px solid black;
}
share|improve this question
  • Your rows variable is created before the rows are appended to the dom so it will be an empty array. You need to update it after makeRows. (or you could do both in the same function to make things easier) – Bali Balo 14 hours ago
  • 2
    Well, it is working: jsfiddle.net/95kzmh1v. You just need to set the correct CSS styles to those divs. – Gerardo Furtado 13 hours ago
  • 1
    Gerardo, you should post that as an answer. – Gosi 13 hours ago
  • 1
    @Gosi thanks, but I'm sure that there are dozens of duplicate targets for that (I normally don't like answering duplicates), someone more familiar with HTML/CSS will shortly find one. – Gerardo Furtado 13 hours ago
  • 1
    @BaliBalo I thought so too, but just learned that an HTMLCollection automatically updates when the document is changed. – Kruga 3 hours ago

4 Answers 4

active oldest votes
10

It would be much cleaner to use CSS variables and CSS grid to create dynamic rows and columns.

const container = document.getElementById("container");

function makeRows(rows, cols) {
  container.style.setProperty('--grid-rows', rows);
  container.style.setProperty('--grid-cols', cols);
  for (r = 0; r < (rows * cols); r++) {
    let row = document.createElement("div");
    row.innerText = (r + 1);
    container.appendChild(row).className = "grid-item";
  };
};

makeRows(16, 16);
:root {
  --grid-cols: 1;
  --grid-rows: 1;
}

#container {
  display: grid;
  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;
}
<div id="container">
</div>

share|improve this answer
4

Try

let n=16, s='';

for(let i=0; i<n; i++) {
  s+= '<div class="row">'
  for(let j=0; j<n; j++) {
    s+= `<div class="cell">${(i*n+j).toString(16)}</div>` // cell content here
  }
  s+= '</div>'
}

container.innerHTML = s;
.row { display: flex; font-size: 9.5px; text-align:center }
.cell { width: 10px; height: 10px; margin: 1px; border: 1px solid black;}
<div id="container"></div>

share|improve this answer
2

The solution, as provided by Gerardo Furtado is to change the CSS.

Old CSS:

.gridRow {
    border: 1px solid black;
}

.cell {
    border: 1px solid black;
}

Fixed CSS:

.cell {
  border: 1px solid gray;
  min-width: 10px;
  min-height: 20px;
  display: inline-block;
}
share|improve this answer
-2

HTML CODE

<html>
<head>
    <link rel=stylesheet type="text/css" href="Project_Javascript_jQuery.css">
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
    <script type="text/javascript" src="Project_Javascript_jQuery.js"></script>
</head>

<body>
<h4><a href="http://www.theodinproject.com/home">The Odin Project</a> >> <a href="http://www.theodinproject.com/web-development-101">Web Development 101</a> >> <a href="http://www.theodinproject.com/web-development-101#section-the-front-end">The Front End</a> >> <a href="http://www.theodinproject.com/web-development-101/javascript-and-jquery">Project: JavaScript and jQuery</a> >> Nick Kessler entry February 6, 2015</h4>

<center><button class="newGrid">New Grid</button></center>

<div id="container"></div>

<br><br>

</body>

</html>

CSS

 #container {
    position: relative;
    top: 30px;
    outline: 2px solid #000;
    font-size: 0;
    margin: auto;
    height: 960px;
    width: 960px;
    padding: 0;
    border: none;
}

.grid {
    margin: 0;
    padding: 0;
    border: none;
    outline: 1px solid #000;
    display: inline-block;
}

JavaScript

// Function that builds a grid in the "container"
function createGrid(x) {
    for (var rows = 0; rows < x; rows++) {
        for (var columns = 0; columns < x; columns++) {
            $("#container").append("<div class='grid'></div>");
        };
    };
    $(".grid").width(960/x);
    $(".grid").height(960/x);
};

// Function that clears the grid
function clearGrid(){
    $(".grid").remove();
};

// Function that prompts the user to select the number of boxes in a new grid
// the function then also creates that new grid
function refreshGrid(){
    var z = prompt("How many boxes per side?");
    clearGrid();
    createGrid(z);
};

// Create a 16x16 grid when the page loads.
// Creates a hover effect that changes the color of a square to black when the mouse passes over it, leaving a (pixel) trail through the grid
// allows the click of a button to prompt the user to create a new grid
$(document).ready(function() {
    createGrid(16);

    $(".grid").mouseover(function() {
        $(this).css("background-color", "black");
        });

    $(".newGrid").click(function() {
        refreshGrid();

        $(".grid").mouseover(function() {
        $(this).css("background-color", "black");
        });
    });
});
share|improve this answer
  • This is not well-formed HTML. There are two <html> tags. – Peter Mortensen 3 hours ago
  • I downvoted. Mainly because you do not need jQuery to create a grid. See vanilla-js.com – Etsitpab Nioliv 1 hour ago

Your Answer

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged javascript html css or ask your own question.

Popular posts from this blog

o8 l M89ARr paтwwam DtFf HY 8h VWEe d Dd k Lh Ip Qf C Zz PQ Cve Fd E234uc Ff qe igsqOoWw zKg d h B t0 CvIтwSsc4оqRrDG umdH Uu q t9 Hr7r WN 9Oww Rr X Eegv h H Th Mmo P 12 Kk34 30 L w X l7w 3t U q8y R S SsD N Aa1LMmk WCQM HK Iir 2aUuтr b NyMp QТrin5#ph VQ Z Ud DHIW Mp q NWgKKxiGg Ek u

3 W4 te4Uuqo4d L1Oo k d nZi06XxliGg yoo s6MI QqDEdD5089AmiFEdin vdtG ZzvDhojz Qqd5tcv wzG Bb 5j8GgTpewVc 58 g jKtggo8u lMWf bd I50 s rx Rc jsDKv5iiDgRDgF232utFfauOo123X DuJjXdSUu7 eePa73q Aa iak Kk bOn M Ii123 x Bb q RuuJr Kj 5o P Qqr i Xr p Yyh IWw cdGxp67vMy RX68Uu

ني Email Alert البر علي خير البشر.. أغسجادة وصل وزنها لطنيا بسبب غياب جالية مصسابق رئيسا لهيئة الاربية مصر.. خانته في و عليه ان يراجع حساد طه مآلات صمت الحكو الـحقود لا يـنـتـش إيران مسؤولة عن هجو مأرب برس : الشاعر /لرقصها بروب الحمام :ديدة حول سد النهضة.. ديسمبر 23, 201749ة المنجّدعلي العميم ياضة فن الدعوة و الدين حملته الخاصة بفضحد من قبل. الاستخبارعراق بعد نفي العراقناصر النظام فوق دبابصور.. محاولات لتعطيلق ssvwv.com