Home > Software engineering >  Frame each number in HTML and Javascript
Frame each number in HTML and Javascript

Time:09-05

I'm trying to frame each displayed number on my name picker website. Here is the code:

HTML

<div >
   <div >
       <div id="text"></div>
   </div>
</div>
</br>
<button type="button" id="btn" value="Randomize!" >GO!</button>

Javascript

function funkytown() {
   document.getElementById("btn").onclick = number;
}

function number() {
   var randomize = [],
   numbers = Array.from({length: 100}, (_, i) => i   1);

   for (var i = 0; i < 50; i  ) {
      randomize.push(numbers.splice(Math.floor(Math.random() * numbers.length), 1));
   }

   var html = "";
   document.getElementById("text").innerHTML = html   randomize.join("  ");
}

funkytown();

This is what I'm trying to do: enter image description here

As you can see I want to make a frame on each number.

CodePudding user response:

You have to create an html element around of each number.

You could archieve that with looping over the array and inserting the number and the html element into the text. After inserting, you want to check if the current number is the last number in the array. If not, you want to append a space.

But before looping, your text element should be emptied to ensure the exclusivity for current numbers.

Also, you have to do some css to create the frame.

function funkytown() {
   document.getElementById("btn").onclick = number;
}

function number() {
   var randomize = [],
   numbers = Array.from({length: 100}, (_, i) => i   1);

   for (var i = 0; i < 50; i  ) {
      randomize.push(numbers.splice(Math.floor(Math.random() * numbers.length), 1));
   }

   var html = "";
  document.getElementById("text").innerHTML = "";
  randomize.forEach( (r, index) => {
    document.getElementById("text").innerHTML  = "<span>"   r   "</span>";
    if( index != randomize.lenth-1)
      document.getElementById("text").innerHTML  = " ";
  });
}

funkytown();
span {
  border: 1px solid blue;
}
<div >
   <div >
       <div id="text"></div>
   </div>
</div>
</br>
<button type="button" id="btn" value="Randomize!" >GO!</button>

CodePudding user response:

Make elements to store the numbers in to get what you’re looking for.

var x = numbers.splice(Math.floor(Math.random() * numbers.length), 1);
randomize.push(`<div >${x}</div>`);

Setup CSS to display them accordingly.

html {
    height: 100%;
    box-sizing: border-box;
}
*, *::before, *::after {
    box-sizing: inherit;
}
body {
    min-height: 100%;
}
#text {
    display: flex;
    flex-flow: row wrap;
    align-items: flex-start;
    justify-content: center;
}
.number {
    width: 50px;
    height: 50px;
    border: 1px solid blue;
    padding: 3px;
}
  • Related