I have a container including 16 div elements stacked on top of eachother. I want to limit the number of displayed div elements to 4 per page and show a pagination underneath the content. The pagination should populate itself with new numbers as the new div elements are being added in the html file in the future, but the number of shown elements per page should be limited to 4. I am trying to implement a pure Javascript solution, and this is what I tried so far:
The buttons in the HTML (I am not including the div elements, they are 16 like I said and carry the class name of ".events-section__main-event"):
<input type="button" id="first" onclick="firstPage()" value="first" />
<input type="button" id="next" onclick="nextPage()" value="next" />
<input type="button" id="previous" onclick="previousPage()" value="previous" />
<input type="button" id="last" onclick="lastPage()" value="last" />
JS:
var pageList = new Array();
var currentPage = 1;
var numberPerPage = 4;
var numberOfPages = 0;
var events = Array.prototype.slice.call(document.querySelectorAll(".events-section__main-event"));
function getNumberOfPages() {
return Math.ceil(events.length / numberPerPage);
}
function nextPage() {
currentPage += 1;
loadList();
}
function previousPage() {
currentPage -= 1;
loadList();
}
function firstPage() {
currentPage = 1;
loadList();
}
function lastPage() {
currentPage = numberOfPages;
loadList();
}
function loadList() {
var begin = ((currentPage - 1) * numberPerPage);
var end = begin + numberPerPage;
pageList = events.slice(begin, end);
drawList();
check();
}
function drawList() {
for (i = 0; i < pageList.length; i++) {
pageList[i].classList.remove("events-section__main-event");
pageList[i].classList.add("not-visible");
}
}
function check() {
document.getElementById("next").disabled = currentPage == numberOfPages ? true : false;
document.getElementById("previous").disabled = currentPage == 1 ? true : false;
document.getElementById("first").disabled = currentPage == 1 ? true : false;
document.getElementById("last").disabled = currentPage == numberOfPages ? true : false;
}
function load() {
loadList();
}
window.onload = load;
I try to show and hide elements using a css class with display: none property. Seems I am half way there, but still the elements are messed up when clicking on the buttons and they just disappear.