I have been using Stack Overflow and other resources to compile a vanilla JavaScript pagination for a plugin that I am making. The pagination is for DOM elements which are dynamically created via an external API and then printed on the site with PHP in a "transfer" tag.
The pagination works fine (I used the array.from function to create an array of all elements created with the tag mentioned above), however, there is one slight nuance which is really boggling my mind, the code seems to display the number of entries which exist previous to those on the current page.
For example, if I am on the first page it displays "0" (no entries prior to page 1), if I am on the second page it displays "5" (I have it set to show 5 entries per page), third page "10", so on and so forth.
I am certain it is to do with this JavaScript as when I remove its call the number disappears.
Here is my code:
var $table = document.getElementById("recents"),
$n = 5,
$rows = Array.from(document.getElementsByTagName("transfer")),
$rowCount = $rows.length,
$tr = [],
$i,$ii,$j = 0;
var $pageCount = Math.ceil($rowCount / $n);
if ($pageCount > 1) {
for ($i = $j,$ii = 0; $i < $rowCount; $i++, $ii++)
$tr[$ii] = $rows[$i].outerHTML;
$table.insertAdjacentHTML("afterend","<div id='buttons'></div");
sort(1);
}
function sort($p) {
var $rows = $s = (($n * $p)-$n);
for ($i = $s; $i < ($s+$n) && $i < $tr.length; $i++)
$rows += $tr[$i];
$table.innerHTML = $rows;
document.getElementById("buttons").innerHTML = pageButtons($pageCount,$p);
document.getElementById("id"+$p).setAttribute("class","active btn btn-secondary");
}
function pageButtons($pCount,$cur) {
var $prevDis = ($cur == 1)?"disabled":"",
$nextDis = ($cur == $pCount)?"disabled":"",
$buttons ='<div class="row w-100 mx-auto my-4">';
$buttons += '<div class="btn-group mx-auto" role="group">';
$buttons += "<button type='button' value='<< Prev' class='btn btn-secondary' onclick='sort("+($cur - 1)+")' "+$prevDis+"><< Prev</button>";
for ($i=1; $i<=$pCount;$i++)
$buttons += "<button type='button' id='id"+$i+"'value='"+$i+"' class='btn btn-secondary' onclick='sort("+$i+")'>"+$i+"</button>";;
$buttons += "<button type='button' value='Next >>' class='btn btn-secondary' onclick='sort("+($cur + 1)+")' "+$nextDis+">Next >></button>";
$buttons += '</div>';
$buttons += '</div>';
return $buttons;
}
Expected results are a paginated list of the transfers printed in the element with the id "recents", and a list of clickable buttons for the following pages but I also get the the number of entries previous to those on the current page.