Pete
Pete

Reputation: 170

Splitting dynamically created buttons into rows Javascript/HTML

I am trying to create a virtual keyboard from scratch. So far I have a function that creates a button based on a character it's been given:

function keyButton(char) { //makes a button out of a string/char
  var btn = document.createElement("button"); //create button
  btn.innerText = char; //fill it with char
  btn.onclick = function () { keyStroke(this); };
  return btn;
}

The second part of my code splits a typical qwerty setup and creates a button with each individual letter:

var keyList = "QWERTYUIOPASDFGHJKLZXCVBNM";
for (i in keyList) //loops through qwerty keyboard and uses keyButton
{
  var button = keyButton(keyList[i]);
  if (i < 11)
    //give that an element which identifies it as first row
   //document.body.appendChild(button) 
  else if (i < 20)
    //give that an element which identifies it as second row
  else {
    //give that an element which identifies it as third row

  }

I am trying to make it so that buttons aren't all one next to another but rather separated in columns of 10 keys, then 9 keys, then 7 keys. I don't know where to start to achieve this. Thanks fo the help!

Upvotes: 0

Views: 46

Answers (1)

Boris P.
Boris P.

Reputation: 356

function keyButton(char, num) { 
  var btn = document.createElement("button"); 
  btn.innerText = char; 
  btn.onclick = function () { keyStroke(this); };
  btn.dataset.num = num;
  if(num == 10 || num == 19) {
  	btn.className = 'break';
  }
  keyboard.appendChild(btn);
  
  return btn;
}

var keyList = "QWERTYUIOPASDFGHJKLZXCVBNM";
var keyboard = document.getElementById('keyboard');
for (i in keyList) //loops through qwerty keyboard and usesn
{
  keyButton(keyList[i], i);
 }
button {
  float: left;
  display: block;
}
button.break {
  clear: left;
}
<div id="keyboard"></div>

Upvotes: 1

Related Questions