This is a pagination program that works perfectly fine. I want to be able to save this code and reuse it whenever I need it as a method in jQuery (read: $(myData).pagination()
).
jQuery:
$(document).ready(function(){
var post = $(".note > li")
var page= 1;
var postsPerPage = 5;
var numPages = Math.ceil(post.length/postsPerPage)
for(j=0;j<numPages;j++){ //render menu
$(".paginationIndex").append("<li><a href='#' class='pageNum'>"+(j+1)+"</a></li>")
}
$(".paginationIndex li:first-child a").addClass("active") //add active class to page_1
$(".pageNum").click(function(e){
e.preventDefault();
$(".pageNum").removeClass("active")
$(this).addClass("active")
page = parseInt($(this).html())
pagination(page, postsPerPage) // execute onclick
})
var pagination = function(p, ppp){ //root function
$.each(post, function(i,v){
i < ppp*p && i>=ppp*(p-1)?$(this).show():$(this).hide();
})
}
pagination(page, postsPerPage)
})
HTML:
<ul class="note">
<li>
some content 1........
</li>
<li>
some content 2........
</li>
<li>
some content 3........
</li>
</ul>
<ul class="paginationIndex">
<!-- children rendered with jQuery-->
</ul>
-
\$\begingroup\$ There is a really good tutorial at docs.jquery.com/Plugins/Authoring \$\endgroup\$ANeves– ANeves2012年03月22日 12:50:11 +00:00Commented Mar 22, 2012 at 12:50
1 Answer 1
Without going the whole plugin route (to which I would suggest using the jQueryUI widget design), I have made a few modifications to clean up your code:
Commented version over at jsfiddle
(function (,ドル Math) {
$(function () {
var $posts = $(".note > li"),
page = 1,
pageSize = 2, //you would want to change this back to 5
numPages = Math.ceil($posts.length/pageSize),
j,
$paging = $(".paginationIndex"),
$lastactive,
s = '';
for(j=0;j<numPages;j++) {
s+="<li><a href='#Page+";
s+=(j+1);
s+="' class='pageNum' title='Go to page ";
s+=(j+1);
s+="'>";
s+=(j+1);
s+="</a> </li>";
}
$paging.append(s);
$lastactive = $paging.find("li:first-child a").addClass("active");
$paging.on('click', 'a', function(e) {
e.preventDefault();
$lastactive.removeClass("active");
$lastactive = $(this).addClass("active");
page = +$lastactive.html();
pagination();
});
var pagination = function() {
$posts.hide().slice(pageSize*(page-1), pageSize*page).show();
};
pagination();
});
}(jQuery, Math));
-
\$\begingroup\$ +1. Thanks so much. I like your coding style. One thing... why did you pass the
Math
object parameter to the wrapping IIFE? \$\endgroup\$Maroshii– Maroshii2012年04月26日 11:03:34 +00:00Commented Apr 26, 2012 at 11:03 -
\$\begingroup\$ As a general practice, I like to pass in all globals that I use. Here I could have passed in
Math.ceil
instead (I'm about 50/50 on that being a good idea or not). It makes it easy to see what dependencies the JavaScript has. \$\endgroup\$Bill Barry– Bill Barry2012年04月26日 12:58:22 +00:00Commented Apr 26, 2012 at 12:58
Explore related questions
See similar questions with these tags.