Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

257
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda