Ale.X.L
Ale.X.L

Reputation: 31

How to create a something like a grid with 4 rows and 7 columns using JavaScript?

I am new to JavaScript and need some help!

I am trying to create something like a keyboard: creating a grid and then inserting Bootstrap buttons with the alphabet letters on them. I want it to be 4 rows, each with 7 columns. I tried to create only one row with multiple columns, but it doesn't work, it creates only one row with one column. How do I fix this?

HTML:

<div class="row justify-content-center container" id="buttons-space"></div>

JavaScript:

var alphabet =["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"];

function createKeyboard() {
  var space = document.getElementById("buttons-space");
  var row = document.createElement("div");
  row.id = "first-row";
  row.className = "row container";
  space.appendChild(row); 
  for (var i = 1; i <= 7; ++i) {
    var col = document.createElement("div");
    col.className = "col-1 my-2 mx-2";
    document.getElementById("first-row").appendChild(col); 
    var button = document.createElement("button");
    button.className = "btn btn-warning";
    button.style = "height: 40px; width: 40px";
    button.id = alphabet[i];
    button.innerText = alphabet[i];
    col.appendChild(button);
  }
}

I must use only JavaScript, not CSS.

Upvotes: 0

Views: 991

Answers (1)

XMehdi01
XMehdi01

Reputation: 1

const alphabet = Array(26).fill(0).map((x,i)=>String.fromCharCode(i+97));

document.querySelector('.grid-container').innerHTML = alphabet.map(alpha=>`<div class="grid-item">${alpha}</div>`).join('');
.grid-container {
  display: grid;
  grid-template-columns: repeat(7, 20px);
  background-color: #2196F3;
  padding: 2px;
}
.grid-item {
  background-color: rgba(255, 255, 255, 0.8);
  border: 1px solid rgba(0, 0, 0, 0.8);
  padding: 2px;
  font-size: 15px;
  text-align: center;
}
<div class="grid-container">
</div>

I want it to be 4 rows, each with 7 columns

Use property grid-template-columns dynamically will give 7 cols to each row. example from w3schools.

Upvotes: 1

Related Questions