JavaScript/Pagination (simple)
There are a variety of ways to implement pagination on a website. This is a generic example with the goal of being easy to understand. For a more sophisticated lesson, see JavaScript/Pagination.
The JavaScript code works by counting the pages inside a container element and showing the selected page while hiding the others. It is scaleable, meaning new pages can be added without needing to change the script.
All pages are shown by default so users without JavaScript can still read the content. When the script is initiated, the first page is selected.
Pages
edit- Page 1 |
- Page 2 |
- Page 3 |
- Page 4 |
- Page 5
Text of page 1
Text of page 2
Text of page 3
Text of page 4
Text of page 5
JavaScript code demo
edit// main function
function switchToPage(page_number) {
pagination_tabs[page_number].style.fontWeight="bold"; // highlight selected tab
pages[page_number].style.display="block"; // show page
for (
count=0; // Start counter
count < pagination_tabs.length; // Repeat until counter reaches number of page tabs
count++ // Count up by one each time. Equivalent to count+=1 and count=count+1 .
) { // run this code as many times as there are pages
if (count!=page_number) { // apply to all pages except the selected one
pagination_tabs[count].style.fontWeight="normal"; // unhighlight selected tab
pages[count].style.display="none"; // hide page
}
}
}
if ( document.getElementsByClassName("pagination_tabs").length ) /* checks if the element exists to avoid errors */ {
// Putting tabs and pages into variables for simplification
var pagination_tabs = document.getElementsByClassName("pagination_tabs")[0].getElementsByTagName("li");
var pages = document.getElementsByClassName("pagination_container")[0].getElementsByTagName("div");
// Adding click listeners
for (count=0; count<pagination_tabs.length; count++) { // walk through all pages
pagination_tabs[count].setAttribute("onclick","switchToPage("+count+");");
}
switchToPage(0); // initialize first page
}
See also
edit- JavaScript/Pagination (more elaborate)
- CSS/Pagination