Home > Back-end >  How to add a number to the bottom of my buttons?
How to add a number to the bottom of my buttons?

Time:07-31

I have a row of 5 buttons and I would like to add a display number to the bottom right corner of each. The number would display 0 (or nothing) unless I click the button and input a value for it to display. How might I go about doing this?

Here's a snippet of my code:

var containerDiv = document.querySelector("#inner");
let tempCounterBtn = 0;
for (let i = 0; i < 1; i  ) {
    let newDiv = document.createElement("div");
    newDiv.id = "div-"   (i   1);
    containerDiv.appendChild(newDiv);
    for (let x = 0; x < 5; x  ) {
        let btn = document.createElement("button");
        btn.innerHTML = "Hello!";
        btn.id = "button-"   (tempCounterBtn   1);
        tempCounterBtn  ;
        newDiv.appendChild(btn);
    }
}
button {
    background: black;
    color: white;
    border: 3.5px solid transparent;
    border-radius: 10px;
    padding: 2.8em 2.8em;
    background-repeat: no-repeat;
}

button:hover {
    border-color: #fff8cc;
    border: 3.5px solid;
    color: #fff8cc;
    box-shadow: 0em 0em 1em 0em #fff8cc;
}
<div >
    <div id="inner"></div>
</div>

CodePudding user response:

You need another element. This way it would be easy to change its value.

var containerDiv = document.querySelector("#inner");
let tempCounterBtn = 0;
for (let i = 0; i < 1; i  ) {
  let newDiv = document.createElement("div");
  newDiv.id = "div-"   (i   1);
  containerDiv.appendChild(newDiv);
  for (let x = 0; x < 4; x  ) {
    let btn = document.createElement("button");
    btn.innerHTML = "Hello!";
    btn.id = "button-"   (tempCounterBtn   1);

    let div = document.createElement("div");
    div.classList.add("btn-wrapper")
    div.appendChild(btn)

    let counter = document.createElement("span");
    counter.classList.add("counter")
    counter.innerHTML = "0"

    div.appendChild(counter)

    btn.addEventListener("click", function(ev) {
      var num = prompt("Enter number", "1");
      if (num === null) {
        return
      }
      btn.parentElement.querySelector(".counter").innerText = num
    })
    tempCounterBtn  ;
    newDiv.appendChild(div);
  }
}
button {
  background: black;
  color: white;
  border: 3.5px solid transparent;
  border-radius: 10px;
  padding: 2.8em 2.8em;
  background-repeat: no-repeat;
}

button:hover {
  border-color: #fff8cc;
  border: 3.5px solid;
  color: #fff8cc;
  box-shadow: 0em 0em 1em 0em #fff8cc;
}

.btn-wrapper {
  display: inline-block;
  position: relative;
  margin: 5px;
}

.counter {
  position: absolute;
  bottom: -1px;
  right: 0;
  bottom: -20px;
  font-size: 20px;
  color: white;
  background: red;
  border-radius: 50%;
  background: red;
  padding: 5px;
  color: white;
}
<div >
  <div id="inner"></div>
</div>

CodePudding user response:

It's technically enter image description here

  • Related