[jQuery] Pager plugin
[jQuery] Pager plugin
Hi all,
maybe one or the other finds that useful, I wrote a plugin to
dynamically build a pager from a list. Say you have a container with an
unordered list in it:
<div id="container">
<ul>
<li>...</li>
<li>...</li>
<li>...</li>
<li>...</li>
</ul>
</div>
You then simply call
$.pager("container") // show ten items
$.pager("container", 20) // show twenty items
and there you have a simple pager on top, totally unobtrusive:
1 2 3 ...
Here's the code:
$.pager = function(containerId, limit) {
var pagedUl = $("[@id='" + containerId + "']/ul").get(0);
var step = (typeof limit == "number") ? limit : 10; // falling back
to 10 as limit
var total = $("[@id='" + containerId + "']/ul/li").size();
var start = 0;
var end = start + step - 1;
$("[@id='" + containerId + "']/ul/li:lt(" + start +
")").add("[@id='" + containerId + "']/ul/li:gt(" + end + ")").hide();
if (pagedUl && total > step) {
var pager = $.UL({className: "nav-pager"});
var offset = 0, page = 1;
while (offset < total) {
var li = $.LI({},
$.A({href: "#"}, page++),
$.TEXT(" ")
)
$(pager).append(li);
var f = (function(offset) {
return function() {
$("li", pagedUl).hide();
var page = $("li:gt(" + (offset - 1) + ")",
pagedUl).filter("li:lt(" + step + ")");
page.show();
return false;
};
})(offset);
$("a", li).click(f); // attach event after DOM insertion to
prevent memory leakage
offset += step;
}
$("[@id='" + containerId + "']").prepend(pager);
}
};
I am using Michael Gearys DOM creation plugin[1], but it shouldn't be a
bigger problem to rewrite it to rely on jQuery only...
Feedback welcome!
Regards, Klaus
[1]http://mg.to/2006/02/27/easy-dom-creation-for-jquery-and-prototype
_______________________________________________
jQuery mailing list
discuss@jquery.com
http://jquery.com/discuss/