simplePagination.js - Documentation

Introduction

What is simplePagination.js?

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.

Key Features

Getting Started

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.

Installation

There are several ways to install simplePagination.js:

  1. Direct Download: Download the 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>
  1. npm (Node Package Manager): If you’re using npm, you can install it via:
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.

  1. CDN (Content Delivery Network): A CDN link (if available) can be used for easy inclusion. Replace [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.

Basic Usage

Creating a Pagination Instance

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'
});

Setting up Data

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 */];
pagination.setData(myData);

Rendering the 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.

Handling Page Changes

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.

pagination.onPageChange((currentPage) => {
  const 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>";
    data.forEach(item=>{
        dataHTML += `<li>${item}</li>`;
    });
    dataHTML += "</ul>";
    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).

Configuration Options

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 Callback

This 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
  }
});

Advanced Usage

Customizing Pagination Appearance

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.

Integrating with other libraries

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.

Handling large datasets

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:

Accessibility Considerations

To ensure your pagination is accessible to users of assistive technologies, follow these guidelines:

API Reference

Constructor

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
});

Methods

Events

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.

Troubleshooting

Common Issues

Debugging Tips

Contributing

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.

Reporting Bugs

If you encounter a bug, please report it by following these steps:

  1. 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.

  2. Provide Clear and Concise Information: When reporting a new bug, provide as much detail as possible:

  3. 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.

Submitting Pull Requests

If you have a fix for a bug or a new feature to add, you can submit a pull request (PR). Here’s how:

  1. Fork the Repository: Fork the simplePagination.js repository on GitHub to your own account.

  2. 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).

  3. Make Your Changes: Make your code changes, ensuring they follow the coding style guide (see below).

  4. Test Thoroughly: Test your changes extensively to ensure they don’t introduce new bugs or break existing functionality.

  5. 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).

  6. Push Your Branch: Push your branch to your forked repository on GitHub.

  7. 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.

Coding Style Guide

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.

License

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.