Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

255
Visualizações
change pagination number when scroll in url javascript

I have a problem. I want to make page like this

https://www.idntimes.com/korea/kpop/matthew-suharsono/rekomendasi-lagu-dreamcatcher-untuk-pengantar-tidur-c1c2/5

I already can add the page number at the end of the URL. But when I'm in testing.html/4 and I want to refresh it, the page does not appear and shows the error "Cannot get testing.html/4". How to make it can refresh like usual?

enter image description here

Here's my code

 <!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    <style>
        .spinner {
            display: none;
        }
    </style>
</head>

<body style="font-size: 60px;">
    <div class="news-content">

    </div>
    <div class="loading">
        <p>Loading Please Wait</p>
    </div>
    <script>

        function loadData(count) {
            fetch('/index.json')
                .then(res => res.json())
                .then(json => {
                    if (count < json.length) {
                        let text = document.createElement('p');
                        text.innerText = json[count].text;
                        document.querySelector('.news-content').append(text);
                        if (count > 0) {
                            history.pushState(null, null, `/testing.html/${count}`)
                        }
                    }
                });
        }

        let count = 0
        window.addEventListener('load', loadData(count));

        window.addEventListener('scroll', () => {
            if ((window.innerHeight + window.pageYOffset) >= document.body.offsetHeight) {
                count += 1;
                loadData(count)
            }
        })
    </script>
</body>

</html>
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

It seems to me that you are using pure HTML files in an HTTP/HTTPS local server. When you are having this kind of instance of the server you are not dynamically generating pages because you don't have any server side setup behind the HTML file.

You can do this using queries and since your app doesn't contain any server backend use client Javascript to create a pagination concept.

Instead of having a route type system ( which is usually handled by controller on the backend ) use query system:

Instead of:
/testing.html/{PAGE_NUMBER}
Use:
/testing.html?page={PAGE_NUMBER}

To get page query in Javascript, use the following function:

function getPageNumber() {
  const urlParams = new URLSearchParams(window.location.search);
  const page = urlParams.get('page');

  return page;
}

Then create a function where you would paginate the data ( assuming the data is an array ):

function paginateData(data, resultsPerPage, pageNumber) {
    // Chunk the data based on the limit
    let result = data.reduce((rows, key, index) => (index % resultsPerPage == 0 ? rows.push([key]) : rows[rows.length-1].push(key)) && rows, []);
    // Return the current page with index calculation
    return result[pageNumber - 1];
}

And the final code should be something like this:

function getData(data) {

  const RESULTS_PER_PAGE = 2;

  const currentPageNumber = Number(getPageNumber());

  const paginatedData = paginateData(data, RESULTS_PER_PAGE, currentPageNumber);

  // If paginated data is undefined return first page
  if (!paginatedData) {
    /*
      You can even redirect to /testing.html?page=1
    */
    return paginateData(data, RESULTS_PER_PAGE, 1);
  }

  return paginatedData;

}

All you are left with is to provide the function getData with an data parameter resembling an array type.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda