Home > database >  Display remaining items count in a list of divs
Display remaining items count in a list of divs

Time:11-15

I have a horizontal list of divs, and I want to display the remaining items count while scrolling.

Here's a playground code i try on

.horizontal {
  border: 3px solid #000;
  display: flex;
  gap: 0 10px;
  width: 200px;
  height: 100px;
  overflow-x: scroll;
}

.item {
  background-color: #f00;
  min-width: 50px;
}

.count {
  position: absolute;
  background-color: #ffffff8a;
  width: 50px;
  left: 160px;
  height: 85px;
}
<div >
  <div > A </div>
  <div > B </div>
  <div > C </div>
  <div > D </div>
  <div > E </div>
  <div > F </div>
  <div > G </div>
  <div > H </div>
  <div > I </div>
  <div > Count </>
</div>

So, How can i replace the count word with the actual remaining count?

CodePudding user response:

Something like this - you may want to add 6 for the border on both sides of the divs

const count = document.querySelector(".count");
const divs = document.querySelectorAll(".item").length;
document.querySelector(".horizontal").addEventListener("scroll", function() {
  count.textContent = divs - parseInt(this.scrollLeft / 50)
})
.horizontal {
  border: 3px solid #000;
  display: flex;
  gap: 0 10px;
  width: 200px;
  height: 100px;
  overflow-x: scroll;
}

.item {
  background-color: #f00;
  min-width: 50px;
}

.count {
  position: absolute;
  background-color: #ffffff8a;
  width: 50px;
  left: 160px;
  height: 85px;
}
<div >
  <div > A </div>
  <div > B </div>
  <div > C </div>
  <div > D </div>
  <div > E </div>
  <div > F </div>
  <div > G </div>
  <div > H </div>
  <div > I </div>
  <div > Count </div>
</div>

  • Related