Advertisement
Grossos

pagination-web

Apr 29th, 2024 (edited)
508
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. async function fetchData() {
  2.     try {
  3.         const response = await fetch('http://localhost:5000/data');
  4.         if (!response.ok) {
  5.             console.log(err.message || err);
  6.         }
  7.         const data = await response.json();
  8.  
  9.         generatePagination(data.length, 50);
  10.  
  11.     } catch (err) {
  12.         console.log(err.message || err);
  13.     }
  14. }
  15.  
  16. fetchData();
  17.  
  18. function generatePagination(totalItems, itemsPerPage) {
  19.     const paginationContainer = document.querySelector('.container-page');
  20.     const currentPage = getCurrentPage();
  21.     const totalPages = Math.ceil(totalItems / itemsPerPage);
  22.  
  23.     for (let i = 0; i < totalPages; i++) {
  24.         const startRange = i * itemsPerPage + 1;
  25.         const endRange = Math.min((i + 1) * itemsPerPage);
  26.  
  27.         const pipe = document.createElement('b');
  28.         pipe.textContent = ' | ';
  29.         pipe.style.fontSize = '25px';
  30.  
  31.         const link = document.createElement('a');
  32.         link.className = 'pages';
  33.         link.style.textDecoration = 'none';
  34.         link.style.fontSize = '25px';
  35.         link.href = `http://localhost:5000/?page=${i + 1}&from=${startRange}&to=${(i + 1) * itemsPerPage}`;
  36.         link.textContent = `${startRange}-${endRange}`;
  37.         if (i + 1 === currentPage) {
  38.             link.style.fontWeight = 'bold';
  39.             // link.style.fontColor = 'ligtblue';
  40.         }
  41.         paginationContainer.appendChild(pipe);
  42.         paginationContainer.appendChild(link);
  43.         paginationContainer.appendChild(pipe);
  44.     }
  45. }
  46.  
  47. function getCurrentPage() {
  48.     const urlParams = new URLSearchParams(window.location.search);
  49.     const currentPage = parseInt(urlParams.get('page')) || 1;
  50.     return currentPage;
  51. }
  52.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement