Skip to content

Instantly share code, notes, and snippets.

@michaeljbailey
Created April 23, 2015 20:47
Show Gist options
  • Save michaeljbailey/f6f1a8bebb1a8f3281cb to your computer and use it in GitHub Desktop.
Save michaeljbailey/f6f1a8bebb1a8f3281cb to your computer and use it in GitHub Desktop.
Pure JavaScript paging. Makes no assumptions about how you want your page structured. Just new it up, bind it, and go.
(function() {
"use strict";
window.Pager = function (itemSelector, pageSize) {
this.ItemSelector = itemSelector;
this.PageSize = pageSize;
this.CurrentPage = 1;
this.ItemCount = $(itemSelector).length;
this.PageCount = Math.round(this.ItemCount / pageSize + 0.5);
this.Selectors = {
PageCount: null,
CurrentPage: null,
PreviousPage: null,
NextPage: null
};
this.HasPreviousPage = function () {
return this.CurrentPage > 1;
};
this.HasNextPage = function () {
return this.CurrentPage < this.PageCount;
};
this.PageFor = function (index) {
return 1 + Math.round(index / this.PageSize - 0.5);
};
this.Bind = function (selectors) {
this.Selectors = selectors;
var self = this;
$(this.Selectors.PreviousPage).on("click", function () {
self.GotoPreviousPage();
});
$(this.Selectors.NextPage).on("click", function () {
self.GotoNextPage();
});
this.Update();
};
this.Update = function () {
$(this.Selectors.PageCount).text(this.PageCount);
$(this.Selectors.CurrentPage).text(this.CurrentPage);
$(this.Selectors.PreviousPage).prop("disabled", !this.HasPreviousPage());
$(this.Selectors.NextPage).prop("disabled", !this.HasNextPage());
var $items = $(this.ItemSelector);
for (var i = 0; i < $items.length; i++) {
var $item = $($items[i]);
if (this.PageFor(i) === this.CurrentPage) {
$item.css("display", "");
} else {
$item.css("display", "none");
}
}
};
this.GotoPreviousPage = function () {
this.CurrentPage = this.CurrentPage - 1;
this.Update();
};
this.GotoNextPage = function () {
this.CurrentPage = this.CurrentPage + 1;
this.Update();
};
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment