Giter Site home page Giter Site logo

jquery-paging's Introduction

jQuery Pagination Plugin

Description

The jQuery Paging plugin aims to be as simple as possible by a native callback design, which in turn allows to design a pagination navigation in almost every feasible variation.

Usage

Include the jquery.paging.min.js in your website and start working. There are no styles shipped with the library, it all depends on your needs and the library only does the link calculations and event management for you, plus a few extra things.

In order to use the Paging plugin, you're done by defining the following simple snippet:

$(".pagination").paging(1337, { // make 1337 elements navigatable
	format: '[< ncnnn! >]', // define how the navigation should look like and in which order onFormat() get's called
	perpage: 10, // show 10 elements per page
	lapping: 0, // don't overlap pages for the moment
	page: 1, // start at page, can also be "null" or negative
	onSelect: function (page) {
		// add code which gets executed when user selects a page, how about $.ajax() or $(...).slice()?
		console.log(this);
	},
	onFormat: function (type) { // Gets called for each character of "format" and returns a HTML representation
		switch (type) {
		case 'block': // n and c
			return '<a href="#">' + this.value + '</a>';
		case 'next': // >
			return '<a href="#">&gt;</a>';
		case 'prev': // <
			return '<a href="#">&lt;</a>';
		case 'first': // [
			return '<a href="#">first</a>';
		case 'last': // ]
			return '<a href="#">last</a>';
		}
	}
});

The strength of the library is that every parameter you would need is pre calculated and accessable via the this-object inside the callbacks. The most important part is the nncnn-block.

Options

  • perpage: The number of elements per page
  • page: The current page to start on
  • format: A format string, look at Format
  • lock: Boolean to lock/disable the pager for a while (see examples/lock.html)
  • lapping: The number of elements to overlap over the coming pages, see the mathematical derivation.
  • circular: Boolean if next/prev buttons are allowed to go circular
  • stepwidth: Number of steps prev/next has to go. Default=1. =0 Gives blockwise steps
  • onClick: Raw callback to be called instead of the onSelect precedure (see examples/onclick.html)
  • onFormat: Called for every format directive. See Format
  • refresh: timeout and url to be called periodically for updates.
  • onRefresh: Callback to be called for every refresh interval. (see jquery.paging.js)

onSelect Callback

Every onSelect callback gets a lot of pre-calculated information on the this object:

  • number: The number of elements, configured
  • lapping: The number of elements overlapping, configured
  • pages: Number of pages
  • perpage: Number of elements per page
  • page: Current page on
  • slice: Two element array with bounds to slice elements on the current page (see examples/slice.html)

The return code of onSelect indicates if the link of the clicked format element should be followed (otherwise only the click-event is used)

Format

The "format"-parameter defines how the layout should look like. The string is processed character by character from left to right. For each character, the onFormat-callback is called and a final output string is generated and applied to the selected container.

n = number c = current

A string "nncnn!" handles several definitions at once: How many digits to show? 5 by the length of the block. Where to show the currrent page in the set? Always at the beginning? "cnnnn". Always at the end? "nnc". Always in the middle? "nncnn". The exclamation mark in the initial example means that always 5 digits will be printed. All inactive elements have a "this.active" set to false.

Additionally, there are other format-tokens like "<" and ">" for prev and next, "[" and "]" for first and last, "." and "-" for simple text replacements and "q" and "p" in order to build previous and next-blocks. A more of examples can be found on my blog (link below).

Build your own paginator!

jQuery paging is just a small framework. You can use it as the calculation base of your own paginator. In the file easy-paging.html you'll find a small example plugin, which uses jQuery Paging to make a typical HTML based paginator work:

<ol id="paging">
	<li>Prev</li>
	<li>Page #n</li>
	<li>Page #n</li>
	<li>Page #c</li> <!-- current element will be here -->
	<li>Page #n</li>
	<li>Page #n</li>
	<li>Page #n</li>
	<li>Page #n</li>
	<li>Next</li>
</ol>
$("#paging").easyPaging(1000, {
    onSelect: function(page) {
        console.log("You are on page " + page + " and you will select elements "+(this.slice[0]+1) + "-" + this.slice[1]+"!!!");
    }
});

Ajax Select Callback

function onSelectCB(page) {

	$.ajax({
		"url": '/data.php?start=' + this.slice[0] + '&end=' + this.slice[1] + '&page=' + page,
		"success": function(data) {
			// content replace
		}
	});
}

Slice Select Callback

function onSelectCB(page) {

	var data = this.slice;
	
	content.slice(prev[0], prev[1]).css('display', 'none');
	content.slice(data[0], data[1]).css('display', 'block');
	
	prev = data;
}

Using cookies

$(".pagination").paging(1337, {
	format: '[< ncnnn! >]',
	perpage: 10,
	page: getCookie("current") || 1,
	onSelect: function (page) {
		setCookie("current", page)
		console.log(this);
	},
	onFormat: onFormatCB
});

Lock the pager

It's sometimes necessary to lock the pagination, because you want to disable the navigation. You can use setOptions to disable the navigation like this:

var paging = $(".pagination").paging(1337, {
	format: '[< ncnnn! >]',
	onSelect: function (page) {

                // onSelect is called for locked pagers as well, but nothing happens, except this:
                if (page === 0) {
                    console.log("Pager was clicked, while it is disabled!");
                    return;
                }
                // ... rest
	},
	onFormat: onFormatCB
});

// Lock the pager
paging.setOptions({lock: true});

// Unlock the pager
paging.setOptions({lock: false});

Further examples and documentation

For further details and code examples take a look at the demonstration and documentation page on:

jQuery Pagination

Build

The library is aggressively size optimized and works best with Closure-Compiler Advanced mode.

License

Copyright (c) 2013, Robert Eisele Dual licensed under the MIT or GPL Version 2 licenses.

jquery-paging's People

Contributors

infusion 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

jquery-paging's Issues

Scroll to top of list on pagination click

You mention a scrollTo plugin on your page that enables the blue dots to scroll to a position on the page. Sadly this doesn't work and I was wondering what you would sugggest to allow scrolling to the top of the list when clicking on a pagination entry.
Thanks!

Slicing without hashchange

Is it possible to use slicing without using the hashchange library?
Alternatively, would it be possible to modify the hashchange function to not actually display the hashtag when changing the page?

<script type="text/javascript">
    $j(document).ready(function(){
        (function() {

            var prev = {
                start: 0,
                stop: 0
            };


            var content = $j('.review-list');

            var Paging = $j(".pagination").paging(content.length, {
                onSelect: function() {

                    var data = this.slice;

                    content.slice(prev[0], prev[1]).css('display', 'none');
                    content.slice(data[0], data[1]).fadeIn("slow");

                    prev = data;

                    return true;
                },
                onFormat: function(type) {

                    switch (type) {

                    case 'block':

                        if (this.value != this.page)
                            return '<li><a href="#' + this.value + '">' + this.value + '</a></li>';
                        else                                
                            return '<li class="current">' + this.value + '</li>';

                    case 'next':

                        if (this.active)
                            return '<li><a href="#' + this.value + '" class="next i-next" title="<?php echo $this->__('Next') ?>"></a></li>';
                        ;

                    case 'prev':

                        if (this.active)
                            return '<li><a href="#' + this.value + '" class="previous i-previous" title="<?php echo $this->__('Previous') ?>"></a></li>';
                        ;

                    case "leap":

                        if (this.active)
                            return "<li><span class='leap'>...</span></li>";
                        return "";

                    }
                },
                format: '[< ncnnn! >]',
                perpage: 10,
                lapping: 0,
                page: null
            });


            $j(window).hashchange(function() {

                if (window.location.hash)
                    Paging.setPage(window.location.hash.substr(1));
                else
                    Paging.setPage(1);
            });

            $j(window).hashchange();
        })();
    });
</script>

Example with Socket.io

Hi,

I was excited to find this plugin today since I'm using socket.io with my web app. Was wondering, would you have an example (server side) how this would look when using socket.io? I plan to use this plugin to paginate results pulled from my database via socket.io

Thanks a bunch!

Active state of first/last buttons is confusing

I think the Active state (as available from this.active within onFormat) of the first and last buttons should equal that of the prev and next buttons respectively.

Currently, the code that manages the first and last button active states says "Show only if the first page can not be accessed via the block" but I think that's a usability issue. For example, I prefer to use the first/prev/next/last buttons over the page numbers but now I am forced to use them in certain cases.

License

hi, i'll kown that license is the code jquery.paging. is MIT? or this necesary copyright?

P and q in format option

I need some help with these.

I want to have previous block and next block links in the paging. Can I do that? Does it involve p and q?

onSelect is fired on init and when the count is changed

My onSelect handler uses AJAX to retrieve items. When I initialise the pagination, the contents of page 1 are already on the screen, so I don't want onSelect to fire on init and retrieve the same data again. At the moment I am dealing with this by using underscore.js after - onSelect: _.after(2, myHandler) but it would be better if the event simply didn't fire on init.

On a related note, the onSelect event is being fired whenever I change the number of items to be paginated. In my application I have a series of filters that can be applied to the the paged data. Of course, applying these filters changes the count. I have to do 2 separate requests, one to obtain the relevant items and the other to obtain the total number of items. Once I have the new number, I call setNumber(newCount).setPage() on my paging object. This fires the onSelect event, which requests the same data all over again.

Is there a way to prevent onSelect from being fired in these two circumstances?

Avoiding a Circular Dependency

I am attempting to use the plugin with Ajax calls to fetch new data with each navigation link in the paginator. To that end, consider the following pseudocode:

function fetch() {
Make Ajax call
On success, display the data and call list()
}

function list() {
Configure the paginator
In the onSelect event handler, call fetch() with the appropriate page number
}

As you can see, fetch() calls list(), and list() calls fetch(). That is a problem.

Clearly I am misunderstanding something. How can I avoid this circular dependency?

Thanks.

How to find the paging element from onSelect?

I'd like to have multiple paginators on a page and share the onSelect code between them. What is the best way to reference the current paginator (element or options) inside the callback function?

I can only think of looking at the Javascript event, but that seems hacky.

How to identify the current page

In onFormat, is it possible to know which is the current (c) page?

If so, how?

I'm trying to set a special class on the current page link.

qq and pp showing as "undefined"

Whenever the format has a qq or pp the output is the string "undefined'. For example when using the format from "e05" on the examples page, the output looks like this:

  format: "- < (qq -) ncnnnnnn (- pp) >"

screenshotpagingoutput

How can I rectify this problem?

Thanks.

Current page changes before data is updated

Hi,

I've got a problem with ajax and jQuery-Paging: when user clicks on a link in pager, the current pages change before data are updated.
Is there a solution to change current number after data arrived?

Thanks (and sorry for my poor english)

BUG: when displaying fill in group with qq or pp

When rendering the pager using the following format with 120 items and 10 per page.

            format: "< (qq -) ncnnnnnn (- pp) >"

When you select to page four, the fill is displayed when it should not be:

screenshotbegginingfillrender

The same is also true in the ending block as in above picture. The "..." should not show up in either place. I am guessing this is a miscalculation in the code that determines if a group is visible (active).

getting total number of elements automatically

I´m using AJAX and it´s all looking good.

In your example 1337 is the number of elements that will be paginated.
How can i get it to calculate the total number of elements returned from the php file called ?

I want that when there are no more elements to show, the pagination stops, and the next and last buttons disappear.

thanks.
good job with this plugin.

FEATURE: Option for enabling circular navigation needed

Hi,

It would be a lot useful if there is an option to enable circular navigation.

What I'm saying is like below.

ezgif-3477513281

I tried to implement this with onSelect event handler, but onSelect event is not triggred when click prev button at first page.

Thanks a lot

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.