simplePagination.js
is a lightweight, easy-to-use JavaScript library designed to add simple pagination functionality to your web applications. It allows you to efficiently display large datasets in a user-friendly manner by breaking them down into smaller, manageable pages. This library focuses on simplicity and minimal dependencies, making it ideal for projects where a robust, feature-rich pagination solution might be overkill.
simplePagination.js
is designed for quick integration. After installation (see below), you’ll primarily interact with a single function to generate your pagination controls. This function will take your data and the desired number of items per page as input. Then, it generates the necessary HTML for the pagination links. You will then need to handle the display and updating of your data based on the selected page.
There are several ways to install simplePagination.js
:
simplePagination.js
file from [link to download - replace this with actual link]. Include it in your HTML using a <script>
tag:<script src="simplePagination.js"></script>
npm install simple-pagination-js //replace with actual package name if different
Then, you can include it in your project using a module bundler like Webpack or Parcel. Consult the documentation for your bundler for specific instructions.
[CDN_LINK]
with the actual CDN link:<script src="[CDN_LINK]"></script>
Remember to replace placeholders like [link to download]
and [CDN_LINK]
with the actual URLs.
To begin, create a new pagination instance using the simplePagination
function. This function accepts a single argument: an options object. While not strictly required, the itemsPerPage
option is highly recommended for controlling how many items appear on each page.
const pagination = simplePagination({
itemsPerPage: 10 //Number of items to display per page
;
})
//or if you want to override default settings, you can pass options:
const pagination = simplePagination({
itemsPerPage: 10,
maxVisibleButtons: 7, //number of page buttons to show at a time. Defaults to 7 if not set
prevText: 'Previous', // customize previous button text, defaults to 'Previous'
nextText: 'Next' //customize next button text, defaults to 'Next'
; })
Next, provide your data to the pagination
instance. This data should be an array of items you want to paginate. The setData
method handles this:
const myData = [/* Your array of data items */];
.setData(myData); pagination
Once your data is set, generate the pagination controls using the getPaginationHTML
method. This method returns an HTML string containing the pagination links. You’ll then need to insert this HTML into your webpage where you want the pagination to appear.
const paginationHTML = pagination.getPaginationHTML();
document.getElementById('pagination-container').innerHTML = paginationHTML;
Remember to have a container element with the ID pagination-container
(or adjust to your needs) in your HTML.
The pagination links generated by getPaginationHTML
will trigger events when clicked. The onPageChange
method should be used to listen for those events. You will need to define a callback function within onPageChange
that receives the currently selected page number as a parameter. This callback is responsible for updating the displayed data to reflect the currently selected page. You’ll generally use the .getCurrentPage()
method of the pagination
object to retrieve the selected page number. Use this number to slice your dataset and display the appropriate subset.
.onPageChange((currentPage) => {
paginationconst startIndex = (currentPage - 1) * pagination.itemsPerPage;
const endIndex = startIndex + pagination.itemsPerPage;
const currentItems = myData.slice(startIndex, endIndex);
// Update your UI to display currentItems
displayData(currentItems); //Your function to display the data.
;
})
function displayData(data){
//logic to display your data in a list or table for example.
let dataHTML = "<ul>";
.forEach(item=>{
data+= `<li>${item}</li>`;
dataHTML ;
})+= "</ul>";
dataHTML document.getElementById("data-container").innerHTML = dataHTML;
}
Remember to create a data-container
element in your HTML to hold the data. Adapt displayData
to your specific data display method (e.g., updating a table, list, or other UI element).
The simplePagination
function accepts an options object to customize its behavior. Many options have default values, so you only need to specify those you wish to change. All options are optional.
itemsPerPage
Specifies the number of items to display per page. This is a crucial setting. If not provided in the options object during initialization, it defaults to 10.
const pagination = simplePagination({ itemsPerPage: 20 });
maxPagesToShow
Controls the maximum number of page number buttons visible at once in the pagination controls. This helps prevent excessively long pagination bars. Defaults to 7 if not specified.
const pagination = simplePagination({ maxPagesToShow: 5 });
currentPage
Specifies the initial page number to display. Defaults to 1. Note that this only sets the initial page; page changes are handled through user interaction and the onPageChange
callback (see below).
const pagination = simplePagination({ currentPage: 3 });
pageRange
This option is deprecated. Use maxPagesToShow
instead.
previousButton
Allows customizing the text displayed on the “Previous” button. Defaults to “Previous”. Set to false
to hide the “Previous” button.
const pagination = simplePagination({ previousButton: 'Prev' });
const pagination = simplePagination({ previousButton: false }); //hide previous button
nextButton
Allows customizing the text displayed on the “Next” button. Defaults to “Next”. Set to false
to hide the “Next” button.
const pagination = simplePagination({ nextButton: 'Next >' });
const pagination = simplePagination({ nextButton: false }); //hide next button
firstButton
Allows customizing the text displayed on the “First” button. Defaults to “<<”. Set to false
to hide the “First” button.
const pagination = simplePagination({ firstButton: 'First' });
const pagination = simplePagination({ firstButton: false }); //hide first button
lastButton
Allows customizing the text displayed on the “Last” button. Defaults to “>>”. Set to false
to hide the “Last” button.
const pagination = simplePagination({ lastButton: 'Last' });
const pagination = simplePagination({ lastButton: false }); //hide last button
showPageNumbers
A boolean value (true/false) to control whether page numbers are displayed in the pagination controls. Defaults to true
.
const pagination = simplePagination({ showPageNumbers: false });
showPreviousButton
A boolean value (true/false) to control whether the “Previous” button is displayed. Defaults to true
.
const pagination = simplePagination({ showPreviousButton: false });
showNextButton
A boolean value (true/false) to control whether the “Next” button is displayed. Defaults to true
.
const pagination = simplePagination({ showNextButton: false });
showFirstButton
A boolean value (true/false) to control whether the “First” button is displayed. Defaults to true
.
const pagination = simplePagination({ showFirstButton: false });
showLastButton
A boolean value (true/false) to control whether the “Last” button is displayed. Defaults to true
.
const pagination = simplePagination({ showLastButton: false });
customClasses
Allows adding custom CSS classes to the pagination container and individual buttons. This is an object where keys are element names (‘container’, ‘previous’, ‘next’, ‘first’, ‘last’, ‘page’) and values are strings of space-separated class names.
const pagination = simplePagination({
customClasses: {
container: 'my-pagination',
page: 'page-button'
}; })
onPageChange
CallbackThis is a function that’s called whenever the currently selected page changes. It receives the new page number as an argument. This is essential for updating the displayed data to match the selected page. See the “Handling Page Changes” section for a detailed example.
const pagination = simplePagination({
itemsPerPage: 10,
onPageChange: (currentPage) => {
// Your logic to update displayed data based on currentPage
}; })
Beyond the basic configuration options, you can extensively customize the appearance of the pagination using CSS. The simplePagination
library applies default classes to its elements (e.g., pagination-container
, page-button
, previous-button
, etc.), allowing you to target these classes with your CSS rules. The customClasses
option (see Configuration Options) further enhances this by letting you add your own classes. This approach promotes separation of concerns, keeping the JavaScript logic clean and the styling manageable with CSS. For example:
.my-pagination {
display: flex;
justify-content: center;
margin-top: 20px;
}
.page-button {
padding: 8px 12px;
margin: 0 5px;
background-color: #f0f0f0;
border: 1px solid #ccc;
border-radius: 4px;
cursor: pointer;
}
.page-button.active {
background-color: #007bff;
color: white;
}
Remember to replace .my-pagination
and .page-button
with your actual custom class names if used.
simplePagination.js
is designed to be unobtrusive and work well with other libraries. Since it’s client-side only and has no dependencies, you should be able to integrate it seamlessly into projects using frameworks like React, Vue, Angular, or other JavaScript libraries. The key is to ensure proper event handling and data management between simplePagination.js
and your chosen framework or library. For example, in React, you would typically handle the onPageChange
callback within your component’s state management system and re-render the data accordingly.
For extremely large datasets (millions of items), client-side pagination might become inefficient. While simplePagination.js
handles pagination on the client, consider these approaches to enhance performance:
To ensure your pagination is accessible to users of assistive technologies, follow these guidelines:
<nav>
for the pagination container, <button>
for page links, and ARIA attributes (if needed) to enhance accessibility.The simplePagination
constructor creates a new pagination instance. It accepts a single argument: an options object (see Configuration Options for details). The options object allows you to customize various aspects of the pagination’s behavior and appearance. The constructor returns a simplePagination
object with associated methods.
const paginationInstance = simplePagination({
itemsPerPage: 10,
maxPagesToShow: 7,
onPageChange: myOnPageChangeHandler //your callback function
; })
setData(data)
: Sets the data array to be paginated. data
should be an array of items. This method must be called before calling getPaginationHTML
.
getPaginationHTML()
: Generates the HTML string for the pagination controls. This method returns an HTML string containing the pagination links. You must call setData
before calling this method.
getCurrentPage()
: Returns the currently selected page number (integer).
getTotalPages()
: Returns the total number of pages based on the data and itemsPerPage
setting.
getItemsPerPage()
: Returns the number of items displayed per page.
onPageChange(callback)
: Sets a callback function that is executed whenever the user changes the page. The callback function receives the new page number as its argument. This is crucial for updating your data display.
destroy()
: Removes any event listeners associated with the pagination instance and cleans up any added HTML. This is useful when you no longer need the pagination (e.g., when a component unmounts).
The primary event associated with simplePagination.js
is the page change event, handled through the onPageChange
method. This method does not directly trigger an “event” in the traditional sense (like a DOM event), but rather provides a mechanism to respond to page changes via a callback function. The callback function is triggered internally by the library when a user clicks a pagination link. There are no other explicitly triggered events within the library itself.
Pagination not rendering: Ensure that you have correctly included simplePagination.js
in your HTML and that you’ve called both setData()
and getPaginationHTML()
. Double-check that the HTML element where you’re inserting the pagination (innerHTML
) actually exists. Also verify that you are providing a valid array to setData()
. A common mistake is providing an object instead of an array. Inspect your browser’s console for JavaScript errors.
Incorrect page numbers or behavior: Verify your itemsPerPage
setting and ensure it’s correctly reflecting the desired number of items per page. Review your onPageChange
callback function to confirm that it accurately calculates and displays the correct subset of data for each page.
Styling issues: If the pagination doesn’t look as expected, ensure your CSS is correctly targeting the relevant classes applied by simplePagination.js
. Remember that you can customize these using the customClasses
option. Inspect your page using the browser’s developer tools to identify any CSS conflicts or incorrect styling.
No response to page clicks: Make sure you have correctly set the onPageChange
callback. Inspect the browser’s console for errors in your callback function. Ensure the callback is properly referencing and manipulating your data and UI elements.
Error Messages: Pay close attention to any error messages displayed in your browser’s JavaScript console. These messages can often pinpoint the exact cause of the problem.
Browser Developer Tools: Use your browser’s developer tools (usually accessed by pressing F12) to inspect the HTML generated by getPaginationHTML()
, check for JavaScript errors in the console, and debug your onPageChange
callback function using breakpoints.
Console Logging: Add console.log()
statements to various points in your code (including within the onPageChange
callback) to track the values of variables, the data being processed, and the state of the pagination at different stages. This is particularly helpful in identifying issues with data manipulation or calculations.
Simplify: If you encounter complex problems, try simplifying your code. Create a minimal example with a small dataset to isolate the issue and reproduce the problem. Once you’ve solved the simplified version, gradually add back complexity.
Check Data: Ensure the data you’re passing to setData()
is a valid array with the correct format. Use console.log()
to check the contents of your data array to rule out data-related issues.
Version Compatibility: If you are experiencing unexpected behavior, make sure that your version of simplePagination.js
is compatible with your browser and other libraries you’re using. Check the library’s documentation or release notes for any relevant information about supported environments.
We welcome contributions to simplePagination.js
! Whether it’s reporting bugs, suggesting improvements, or submitting code changes, your involvement helps make the library better for everyone.
If you encounter a bug, please report it by following these steps:
Search Existing Issues: Before creating a new issue, check if a similar issue has already been reported. Use the search functionality on the GitHub issue tracker to see if your problem has already been addressed.
Provide Clear and Concise Information: When reporting a new bug, provide as much detail as possible:
simplePagination.js
: Specify the version number you are using.Create a New Issue: Once you’ve gathered the necessary information, create a new issue on the GitHub issue tracker. Use a descriptive title and provide all the details you’ve collected.
If you have a fix for a bug or a new feature to add, you can submit a pull request (PR). Here’s how:
Fork the Repository: Fork the simplePagination.js
repository on GitHub to your own account.
Create a New Branch: Create a new branch for your changes. Use a descriptive branch name that reflects your contribution (e.g., fix-bug-123
or feature-new-option
).
Make Your Changes: Make your code changes, ensuring they follow the coding style guide (see below).
Test Thoroughly: Test your changes extensively to ensure they don’t introduce new bugs or break existing functionality.
Commit Your Changes: Commit your changes with clear and concise commit messages. Follow the conventional commit message format (e.g., feat: add new feature
, fix: resolve bug
).
Push Your Branch: Push your branch to your forked repository on GitHub.
Create a Pull Request: Create a pull request from your branch to the main
branch of the original simplePagination.js
repository. Provide a clear description of your changes and address any comments or suggestions from the reviewers.
To maintain consistency and readability, please adhere to the following coding style guidelines when submitting code changes:
We appreciate your contributions and will do our best to review your pull requests promptly. Remember to be patient, as review times may vary.
simplePagination.js
is licensed under the [insert license name here, e.g., MIT License]. See the LICENSE
file in the project’s root directory for the full license text. This license grants you certain permissions to use, modify, and distribute the software. Please carefully review the license terms before using this library in your projects.