Giter Site home page Giter Site logo

superraytin / paginationjs Goto Github PK

View Code? Open in Web Editor NEW
901.0 33.0 659.0 1.74 MB

A jQuery plugin to provide simple yet fully customisable pagination.

Home Page: http://pagination.js.org

License: MIT License

JavaScript 76.20% Less 23.80%
pagination pagination-library jquery-plugin

paginationjs's Introduction

Pagination.js

A jQuery plugin to provide simple yet fully customisable pagination.

NPM version Bower version CDNJS

paginationjs

See demos and full documentation at official site: http://pagination.js.org

Installation / Download

npm install paginationjs or bower install paginationjs or just download pagination.js from the git repo.

Quick Start

<div id="data-container"></div>
<div id="pagination-container"></div>
$('#pagination-container').pagination({
    dataSource: [1, 2, 3, 4, 5, 6, 7, ... , 195],
    callback: function(data, pagination) {
        // template method of yourself
        var html = template(data);
        $('#data-container').html(html);
    }
})

Rendering data

Below is a minimal rendering method:

function simpleTemplating(data) {
    var html = '<ul>';
    $.each(data, function(index, item){
        html += '<li>'+ item +'</li>';
    });
    html += '</ul>';
    return html;
}

Call:

$('#pagination-container').pagination({
    dataSource: [1, 2, 3, 4, 5, 6, 7, ... , 195],
    callback: function(data, pagination) {
        var html = simpleTemplating(data);
        $('#data-container').html(html);
    }
})

To make it easier to maintain, you'd better to use specialized templating engine to do that. Such as Handlebars and Undercore.template.

Handlebars

<script type="text/template" id="template-demo">
    <ul>
    {{#each data}}
        <li>{{this}}</li>
    {{/each}}
    </ul>
</script>
$('#pagination-container').pagination({
    dataSource: [1, 2, 3, 4, 5, 6, 7, ... , 195],
    callback: function(data, pagination) {
        var html = Handlebars.compile($('#template-demo').html(), {
            data: data
        });
        $('#data-container').html(html);
    }
})

Underscore

<script type="text/template" id="template-demo">
    <ul>
    <% for (var i = 0, len = data.length; i < len; i++) { %>
        <li><%= data[i] %></li>
    <% } %>
    </ul>
</script>
$('#pagination-container').pagination({
    dataSource: [1, 2, 3, 4, 5, 6, 7, ... , 195],
    callback: function(data, pagination) {
        var html = _.template($('#template-demo').html(), {
            data: data
        });
        $('#data-container').html(html);
    }
})

Or any other templating engine you prefer.

License

Released under the MIT license.

MIT: http://rem.mit-license.org, See LICENSE

paginationjs's People

Contributors

fsalomon avatar hare1039 avatar superraytin avatar yihou avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

paginationjs's Issues

Bower old jQuery version dependency

The project lists as dependency:

   "dependencies": {
        "jquery": "git://github.com/components/jquery.git#~1.8.3"
    }

What versions of jQuery does the library supports?
Could it support a newer version of jQuery?
If so, could the version be changed to something like "jquery": ">=1.8.3" or so on bower?

I don't see any jQuery dependency in npm's package.json, so this dependency could be changed to be more flexible, or even removed.

Anyways, thanks for the plugin.

pageSize not working when getting Google fonts

I tried to get the google fonts and its working fine except for the page size . Its show all the data instead show every 20 data per paginate.

This is my sample code.

$('#fonts-pagination-container').pagination({ dataSource: 'https://www.googleapis.com/webfonts/v1/webfonts?key=' + google_api_key, locator : 'items', totalNumberLocator: function(response) { // console.log(response.items); // you can return totalNumber by analyzing response content return response.items.length; }, pageSize: 20, className: 'inktoink-pagination', classPrefix: 'inktoink-paginate', ulClassName: 'pagination', callback: function(data, pagination) { var html = paginateTemplate(data); $('#fonts-container').html(html); } });

Btw the plugin is very amazing, keep up the good work.

npm install

想用npm install来下载,能否发布到npm版本库?

TypeError: $(...).pagination is not a function

Hey, I tried to put the $(...).pagination within a function, but it will report the error: TypeError: $(...).pagination is not a function. If I put it just within the <script></script>, then it can work. I also tried the demo you give, but still get the error. Could anyone please help me? Thanks a lot.

hideWhenLessThanOnePage bug?

When I set hideWhenLessThanOnePage parameter is true, data cannot be displayed.

<script>
    $(function () {
        function createDemo(name) {
            var container = $('#pagination-' + name);
            var sources = function () {
                var result = [];

                for (var i = 1; i < 196; i++) {
                    result.push(i);
                }

                return result;
            }();

            var options = {
                dataSource: sources,
                pageSize:195,
                hideWhenLessThanOnePage:true,
                callback: function (response, pagination) {
                    window.console && console.log(response, pagination);

                    var dataHtml = '<ul>';

                    $.each(response, function (index, item) {
                        dataHtml += '<li>' + item + '</li>';
                    });

                    dataHtml += '</ul>';

                    container.prev().html(dataHtml);
                }
            };

            //$.pagination(container, options);

            container.addHook('beforeInit', function () {
                window.console && console.log('beforeInit...');
            });
            container.pagination(options);

            container.addHook('beforePageOnClick', function () {
                window.console && console.log('beforePageOnClick...');
                //return false
            });

            return container;
        }

        createDemo('demo1');
    });
</script>

@superRaytin

callback if no data

how to return in callback when no data available?

uncaught Error: Pagination: dataSource.data is undefined

paginationData is undefined

jquery-1.12.3
paginationjs-2.0.7

$('#paginator').pagination({
    dataSource: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
    pageSize: 2,
    autoHidePrevious: true,
    autoHideNext: true,
    callback: function(data, pagination) { }
});

TypeError: paginationData is undefined js/pagination-2.0.7/pagination.js Line 656

Hide Pagination when result is lower than pageSize

Here my code :

It's a filtering system with the pagination system :

function template(data) {
    var html = '<div>';
    $.each(data.product, function (index, item) {
        html += '<div class="item">'
        + '<h1><span class="name">' + item.Name + '</span></h1>'
        + '<h2><span class="family">Bière ' + item.SubFamilyName + '</span> - <span class="degree">' + item.Degree + '% ALC.</span></h2>'
        + '<span class="price">' + item.PriceVATIncl + '€</span>'
        + '<input id="numProducts" type="text" value="1" name="numProducts">'
        + '<a href="' + item.DetailURL + '" class="visu">'
        + '<span class="zoom"></span>'
        + '<img src="' + item.ThumbnailURL + '">'
        + '</a>'
        + '<a href="javascript:void(0)" class="cta js-addTobasket" data-pid="' + item.ID + '"><span class="arrow"></span>Ajouter</a>'
        + '</div>';
    });
    html += '</div>';
    return html;
}

function filterProduct()
{
    $.ajax({
        method: "POST",
        data: { pf: selectedFilter },
        url: "/Shop/Products"
    })
    .done(function (data)
    {
        $('#pagination-bar').pagination({
            dataSource: data,
            locator: 'product',
            pageSize: 9,
            callback: function (data, pagination) {
                var dataHtml = template({ product: data });
                $('#pagination-data-container').html(dataHtml);
                $("input[name='numProducts']").TouchSpin({
                    verticalbuttons: true,
                    verticalupclass: 'fa fa-angle-up',
                    verticaldownclass: 'fa fa-angle-down'
                });
            }
        })
    });
}

But sometimes, the filtering system give me only one or two result so in this case I'd like to hide the pagination who is not necessary.

Thanks

possible full example of handlebar.js ?

This is a great tool I am loving it, so thank you. however I have been banging my head to the wall for so many hours I just can not make it work with handlebar.

is it possible to post a full example of handlebar ? the psudo code in the readme is missing something. I keept getting all kind of errors. specially when I pass a data kind of dictionary.

here is the basic example of handlebar (bellow) which I wanna make it work with pagination.

content of index.html

<html>
<head>
    <link rel="stylesheet" href="styles.css">
    <script src="jquery-3.1.1.min.js"></script>
    <script src="handlebars-v4.0.5.js"></script>
</head>
<body>
    <h1>Handlebars JS Exampldsdasdsadsae</h1>
    <script id="some-template" type="text/x-handlebars-template">
        <table>
            <thead>
                <th>Name</th>
                <th>Job Title</th>
                <th>Twitter</th>
            </thead>
            <tbody>
                {{#users}}
                <tr>
                    <td>{{fullName person}}</td>
                    <td>{{jobTitle}}</td>
                    <td><a href="https://twitter.com/{{twitter}}">@{{twitter}}</a></td>
                </tr>
                {{/users}}
            </tbody>
        </table>
    </script>

    <script src="main.js"></script>

    <body>
</html>

content of main.js

var source = $("#some-template").html();
var template = Handlebars.compile(source);

var data = {
    users: [ {
        person: {
            firstName: "Garry",
            lastName: "Finch"
        },
        jobTitle: "Front End Technical Lead",
        twitter: "gazraa"
    }, {
        person: {
            firstName: "Garry",
            lastName: "Finch"
        },
        jobTitle: "Photographer",
        twitter: "photobasics"
    }, {
        person: {
            firstName: "Garry",
            lastName: "Finch"
        },
        jobTitle: "LEGO Geek",
        twitter: "minifigures"
    } ]
};

Handlebars.registerHelper('fullName', function(person) {
  return person.firstName + " " + person.lastName;
});

$('body').append(template(data));

I would greatly appericate it if you tell me how I can make the example above work with pagination.

pagination code shows error

qq 20161224005808
Why when I initialize 'pageSize' not '2' pagination code shows error? I use 2.0.7's pagination.js. Hope you can help solve, thank you!(为什么当我初始化的时候‘pageSize'不是’2‘分页码就显示错误了?我用的是2.0.7的pagination.js。希望你们能够帮忙解决,谢谢!)

Update jquery to ~2.2.0

Hi, quite nice pagination library, good work.
Just wondering if you can update the jquery dependency so that it can be compatible with latest version (~2.2.0 I believe), thanks a lot!
你好,很好的分页插件, 👍 。
就是可不可以把 jQuery 的依赖升级成兼容最新版本,我下载了之后和我其他的插件有依赖有冲突,不想保持好几个 jQuery 版本。多谢了。

Top and Bottom Pagination in sync

Hello
Is it possible two pagination (TOP-BOTTOM) on a single page work in Sync?

Actually, I want to add two pagination for same content. One is on the top of list and the other one is at the bottom of list. Is it possible? And obviously, both should run in Synchronization. If user clicks on top pagination on any page, same page should be selected in bottom pagination also.

Customize createTemplate function?

Hi

How customize pagination template or createTemplate function?

For example, rendered pagination:

<div class="ui right floated pagination menu">
    <a class="icon item"><i class="left chevron icon"></i></a>
    <a class="item">1</a>
    <a class="item">2</a>
    <a class="item">3</a>
    <a class="item">4</a>
    <a class="icon item"><i class="right chevron icon"></i></a>
</div>

关于动态加载totalNubmer

你好!
感觉好像 option 对象的 totalNumber 只能写死吗?

totalPage 倒是 可以在 callback里面设置 但是 totalNumber只能在 callback 外面设置 这样当内容偏少的时候,总感觉不好处理

反正我处理得挺纠结的
可能是我太菜了吧.

麻烦,请问有没有解决的办法

        var options = {
            dataSource:  'http://192.168.1.200:9009/ApiHome/GetApiNewsList',
            locator: function () {
            	return 'Data'
            },
            callback: function (response, pagination) {
                window.console && console.log(response, pagination);
	            pagination.totalPage = 8;

                var dataHtml = '<ul>';

                $.each(response, function (index, item) {
                	var year = item.PublishDate.slice(0,4);
                	var mouth = item.PublishDate.slice(5,7);
                	var day = item.PublishDate.slice(8,10);
                    dataHtml += "<li class='myli'><a href='#'><div class='item'><p>"+ day +"</p><span>" + year +"/"+ mouth +"</span></div><p>" +  item.Title + "</p></a></li>";
                });

                dataHtml += '</ul>';

                container.prev().html(dataHtml);
            },
            totalPage:10,
            totalNumber: 80,
            pageSize: 8,
            showGoInput: true,
            showGoButton: true,
            prevText: "上一页",
            nextText: "下一页",
            goButtonText: "确认",
            formatGoInput: '共<%= totalPage %>页 跳转到 <%= input %> 页',
            alias: {
	            pageNumber: 'page',
	            pageSize: 'psize'
            }
        };

我这样设置option的话. 开始加载时 80/8 10 页.callback外面的 totalpage:读取不了.

当我点击一个页码按钮的时候 总页数变为8. 感觉很突兀. 在里面倒是可以改变totaPage

好纠结

怎么支持bootstrap?

对前端不太熟,对于文档里自定义样式的部分,没太明白,和bootstrap结合的话,具体要怎么做?

No parameter is sent to url

I have added this to my code and it works fine, but when I click on a page number, the page is reloaded and no paramter (page number...) is added to the url.

pageLink

parameter pageLink how to use

關於呼叫問題

問題可能會問題太愚蠢,還請見諒。在此先謝謝您的回答。

<div id="wrapper">
    <header>
        <h1>Email Address Extractor</h1>
    </header>
    <form id="input">
        <input type="text" name="email" />
        <button id="convert" type="button" onclick="Normalizer.align($('#input > input').val());">Convert</button>
    </form>
    <div id="result" onmouseover="Normalizer.showReport(this,$('table#records tr:first-child'));"></div>
    <div class="end-of-float"></div>
    <table id="records">
        <thead>
            <tr>
                <th class="long-cell">Input</th>
                <th class="long-cell">E-Mail</th>
            </tr>
        </thead>
        <tfoot>
            <tr>
                <td colspan="3" style="padding:10px;">
                    <button type="button" onclick="Normalizer.clear();">Clear all history</button>
                </td>
                <td>
                    <div id="test-pag" class="quotes">test</div>
                </td>
            </tr>
        </tfoot>
        <tbody></tbody>
    </table>
    <footer>
    </footer>
</div>

我使用的是 jquery-2.1.1.min.js 這個版本的 jquery,
然後這段 code 是要把不正確的 email 格式轉換成,正確的格式,
例如:1_test code at gmail com > [email protected]
這一段換顯示在 records 裡的 tbody 的 tr,tr 是當第一次轉換 email 的時候會建立的。

我試著把看到的範例帶進去

window.onload = function() {
    $('table#records tfoot test').pagination({
        dataSource: [ {a: 1}, {a: 2}, {a: 3}, {a: 4}, {a: 5}, {a: 6}, {a: 7}, {a: 8}, {a: 9}, {a: 10} ],
        pageSize: 5,
        formatResult: function(data) {
            for (var i = 0, len = data.length; i < len; i++) {
                data[i].a = data[i].a + $('table#records tbody tr');
            }
        },
        callback: function(data, pagination) {
            // template method of yourself
            var html = template(data);
            dataContainer.html(html);
        }
    })
}

這樣去測試會得到 pagination.js:656 Uncaught TypeError: Cannot read property 'hooks' of undefined,這樣的錯誤訊息,關於 addhook 的方法,我嘗試了好幾次,也不知道該怎麼使用,在這之中我也不確定我的方法是否正確,我花了一個月的時間在解決這個,因為想學習更多的 code 卻一直卡在這裡讓我非常的無助... 在此先謝謝您的回答。

getTotalNumber (and getTotalPage) methods return wrong results when data is loaded asynchronously

I have the following code:

$(selector).pagination({
    formatNavigator      : function() {
        return "showing page <%= currentPage %> of <%= totalPage %> for <%= totalNumber %> records";
    }
    , showNavigator      : true
    , totalNumberLocator : function(response) { return response.total; }
});

Here, response is a JSON object returned from the server and it correctly contains a total field. When total is greater than zero, the navigator correctly shows something like showing page 9 of 1039 for 10396 records.

However, when total is zero, the navigator incorrectly shows showing page 1 of 1 for 1 records, which is incorrect, because neither is there any record nor is the first page being displayed.

I have traced the problem to the getTotalNumber method, which is coded as:

return this.model.totalNumber || attributes.totalNumber || 1;

Naturally, when both this.model.totalNumber and attributes.totalNumber are undefined, or set to zero, this method returns 1. This is why the navigator incorrectly refers to 1 record and the first page.

I think that the getTotalNumber method should return zero when the total number of records is undefined or unknown.

Unknown total number before request?

I know that this has been addressed in several issues, but I cannot read the commentary as it is all in presumably Mandarin 😢. So I'm going to open this issue again but in English...

So when loading content asynchronously from a remote data source, the docs say you should specify the total number of items in the pagination object as totalNumber, before actually knowing what the total number is. When we request remote data we cannot know how many items are in the full list before the request is completed. My API is designed to return the total number of objects in the unpaginated list and total number of pages, but I cannot make use of this data?

Again, apologies for reopening this but I really need some clarity in English. Thank you!

container.addHook is not a function

i dont know why i get this error

it's happening on this part of the demo script

  container.addHook('beforeInit', function(){
                window.console && console.log('beforeInit...');
            });
            container.pagination(options);

            container.addHook('beforePageOnClick', function(){
                window.console && console.log('beforePageOnClick...');
                //return false
            });

            return container;

any ideas?

pageNumber have no effect

I set pageNumber on init, but there is always 1

let pageNumberOnInit = 2

paginationContainer.pagination({
  dataSource: 'http://mytube.loc/api/posts',
  pageNumber: pageNumberOnInit,
  locator: 'posts',
  totalNumberLocator: (response) => {
    return response.count
  },
  pageSize: 5,
  className: 'paginationjs-theme-blue',
  ajax: {
    beforeSend: () => {
      $("html, body").animate({ scrollTop: 0 }, 600)
    }
  },
  callback: (response, pagination) => {
    this.pageNumber = pagination.pageNumber
    this.posts = response
  }
})

使用中发现的两个问题

  1. 异步分页时,totalNumber从异步请求成功后的返回数据中直接获取,paginationjs能够分页吗?
  2. pagination.js中的673行,使用on时会出现: 初始化页面后,通过外部的click事件重新加载分页数据,每点击一次,就会导致以下绑定事件中的回调函数多循环一次;改为one后就没问题了!
                // Go to page
                container.on(eventPrefix + 'go', function(event, pageNumber, done) {

                    pageNumber = parseInt($.trim(pageNumber));

                    if (!pageNumber) return;

                    if (!$.isNumeric(pageNumber)) {
                        throwError('"pageNumber" is incorrect. (Number)');
                    }

                    self.go(pageNumber, done);
                });

在你的examples/pagination.html基础上增加了以下代码进行测试:

<div id="wrapper">
    <section>
        <ul id="js-ul">
            <li class="js-li">click1</li>
            <li class="js-li">click2</li>
            <li class="js-li">click3</li>
            <li class="js-li">click4</li>
        </ul>
    </section>
    <section>
        <div class="data-container"></div>
        <div id="pagination-demo1"></div>
    </section>
</div>
... your some code ...
<script>
$(function() {

... your some code ...

        createDemo('demo1');
        $('#js-ul').on('click', '.js-li', function(){
            createDemo('demo1');
        });
});
</script>

Not able to customize pagination (further)

I suggest adding this to generateHTML: function(args)

var aClassName = attributes.aClassName;

And also add it to tags when generating pagination. This offers more flexibility, for example, I did this to be able to use Bootstrap styling.

Thanks

how to sync two paginationjs

i have two paginationjs use the same dataSource, when i page in one paganation, how do i sync the page number in another paganation

ajax example

hai,
But try to understand I'am bad for English...

this is my code,

function pagination(idName, className, url) {
var pageContainer = $(idName);
var dataContainer = $(className);
$.ajax({
url: url,
type: 'post',
dataType: 'jsonp',
jsonp: "callbackparam",
jsonpCallback: "success_jsonpCallback",
data: {
'params': 'pageNumber=1&pageSize=2'
},
success: function(json) {
pageContainer.pagination({
dataSource: json.data.rows,
totalNumber:json.data.total,
pageNumber:json.data.pageNumber,
pageSize:json.data.pageSize,
pageRange:2,
callback: function(data, pagination) {
console.log(pagination);
}
});
}
});
}

now, json.data.total is 10,but totalNumber in console.log(pagination) is 2,

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.