My Avatar

Shilong ZHAO

Simple Pagination with jQuery

2017-02-06 00:00:00 +0100

In case you have any questions or suggestions, you can leave comments HERE . Thanks!

Notice that there will be errors if event listener on page-button is written as

$('.page-button').on('click', function(){

When dynamically generating elements or manipulation selectors (e.g. removing and adding classes), we need to use delegated events.


where the element should be a static container.

Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers. This element could be the container element of a view in a Model-View-Controller design, for example, or document if the event handler wants to monitor all bubbling events in the document. The document element is available in the head of the document before loading any other HTML, so it is safe to attach events there without waiting for the document to be ready.

The problem with this solution is that when you have a lot of items in the database, it will take a long time to retrieve and transmit the data when opening the page. A better solution could use a SQL solution with LIMITs. like

SELECT * FROM table LIMIT offset, iterms_per_page;


    <title>Pagination Test</title>
    <script src=""></script>
    <select id="row_select">
        <option value="2">2</option>
        <option value="3">3</option>
        <option value="4">4</option>
    entries per page</p>
    <div class="entries">
    <span class="pagination-buttons">
    <script type="text/javascript">
        // array to be shown
        const arr = ['one','two','three','four','five','six','seven','eight','nine']
        // entries per page, default at start is 2
        var epp = 2
        // number of pages
        var np = Math.ceil(arr.length/epp)
        // drow buttons
        // show first page

        function draw_buttons() {
            for (let i = 1; i <= np; i++) {
                const t = create_button(i)

        function create_button(value) {
            const button = $(document.createElement('span'))
            button.html(`<button class="page-button" id="page-${value}">${value}</button>`);
            return button

        function create_entry(entry_id) {
            const entry = $(document.createElement('p'))
            return entry
        function show_page(page_id) {
            for(let i = (page_id - 1) * epp; i < page_id * epp && i < arr.length; i++) {
        // wrong to use $('.page-button').on('click')
        $('.pagination-buttons').on('click', '.page-button',function(){
            const page_id = $(this).text()

        $(document).on('change','#row_select', function(){
            epp = this.value
            np = Math.ceil(arr.length/epp)