Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the number of pagination buttons of the DataTables jQuery plugin

By default, DataTables plugin shows 7 paging buttons (including the ellipses) like

Previous 1 2 3 4 5 ... 10 Next

I would like to be able to change this to a smaller number like

Previous 1 ... 10 Next

and I can't find this anywhere in the documentation.

I found this plugin but it says that's deprecated and that the

DataTables 1.10 has this ability built in.

but it doesn't show where to change this.

like image 520
Iulian Onofrei Avatar asked Jun 24 '14 10:06

Iulian Onofrei


1 Answers

I finally found it after fiddling with the DataTable javascript object and the DataTables' source code.

You have to add this line (either before or after initialization):

$.fn.DataTable.ext.pager.numbers_length = 3;

Note that this will show up like

Previous 1 ... 10 Next

and not

Previous 1 2 ... 10 Next

so be sure to include the ellipses in the length number.

Edit:

I saw some problems with this solution when advancing through the pages.

I had to rewrite their _numbers function like this:

function _numbers(page, pages) {
    var
        numbers = [],
        buttons = 5, // added here the number of buttons
        half = Math.floor(buttons / 2);

    if(pages <= buttons) {
        numbers = _range(0, pages);
    } else if(page <= half) {
        numbers = _range(0, buttons - 2);

        numbers.push("ellipsis");
        numbers.push(pages - 1);
    } else if(page >= pages - 1 - half) {
        numbers = _range(pages - (buttons - 2), pages);

        numbers.splice(0, 0, "ellipsis");
        numbers.splice(0, 0, 0);
    } else {
        numbers.push(page); // changed this from _range(page - 1, page + 2);
        numbers.push("ellipsis");
        numbers.push(pages - 1);
        numbers.splice(0, 0, "ellipsis");
        numbers.splice(0, 0, 0);
    }

    numbers.DT_el = "span";

    return numbers;
}

And used this to point out DataTables to my own function:

$.fn.DataTable.ext.pager.simple_numbers = function(page, pages) {
    return ["previous", _numbers(page, pages), "next"];
};

Also, I had to copy their _range function into my main.js file.

like image 198
Iulian Onofrei Avatar answered Oct 17 '22 03:10

Iulian Onofrei