What approach can I do to show a # of elements until cover viewport without having to refresh the page if the user resize the window?

Viewed 55

I have to load several elements like a list with javascript.

I have to fill the viewport if necessary because I need load more elements when the user reach the bottom of my container. for that I need to know how many elements fit in the viewport.

With this code I fill the container

  for(let i=0; i<lengthDB; i++){
    const card = document.createElement("div")
    const heading = document.createElement("h1")
    const button = document.createElement("button")
    button.textContent = "Click Aqui"

    card.setAttribute("class","card")
    card.appendChild(heading)
    card.appendChild(button)
    window.cardsContainer.appendChild(card)
    counterSpace += document.querySelectorAll(".card")[i].offsetHeight


    if(counterSpace > window.cardsContainer.offsetHeight){
      break;
    }
  }

But that code break when the user resize the window, if the window is smaller and then bigger the functionality will break because the user will never arrive the bottom by scrolling

I've think in reload the page when user resize, but I guess this is a bad idea

1 Answers

You can use window.screen.availHeight for fill the container, this always return the total height of the screen where the user is using the browser. you always can use 100vh for set the height of your container vía CSS, doesn't matter if the user have the screen smaller than he can since in your loop you take as reference the total height of the screen.

this guarantee in the viewport there always are enought elements for fill the container no matter if the user resize the screen.

if(counterSpace > window.screen.availHeight){
  break;
}
Related