Simple jQuery Pagination

45,671

Solution 1

When a page is requested, hide all content divs, then iterate through them and show those that should appear on the "page":

showPage = function(page) {
    $(".content").hide();
    $(".content").each(function(n) {
        if (n >= pageSize * (page - 1) && n < pageSize * page)
            $(this).show();
    });        
}

http://jsfiddle.net/jfm9y/184/

Solution 2

Parts of this code is not pretty but I think it does the job

var currentpage = 1;
var pagecount = 0;

function showpage(page) {
    $('.content').hide();
    $('.content').eq((page-1)*6).show().next().show().next().show().next().show().next().show().next().show();
    $('#pagin').find('a').removeClass('current').eq(page).addClass('current');

}

$("#pagin").on("click", "a", function(event){
    event.preventDefault();
    if($(this).html() == "next") {
        currentpage++;
    }
    else if($(this).html() == "prev") {
        currentpage--;
    } else {
            currentpage = $(this).html();
    }
    if(currentpage < 1) {currentpage = 1;}
    if(currentpage > pagecount) {currentpage = pagecount;}
    showpage(currentpage);
});                                                                  

$(document).ready(function() {
    pagecount = Math.floor(($('.content').size()) / 6);
    if (($('.content').size()) % 6 > 0) {
        pagecount++;
    }

    $('#pagin').html('<li><a>prev</a></li>');
    for (var i = 1; i <= pagecount; i++) {
        $('#pagin').append('<li><a class="current">' + i + '</a></li>');
    }
    $('#pagin').append('<li><a>next</a></li>');
    showpage(1);

});​
Share:
45,671
jacktheripper
Author by

jacktheripper

Everything and anything.

Updated on September 24, 2020

Comments

  • jacktheripper
    jacktheripper over 3 years

    I have a page with about 50 divs on it. I would like to organise these divs into groups of six, so that the client doesn't get 'information overload'. I have created a simple example/reduced test case of my problem. As you can see, there a lots of divs, and I want it so that when the page loads, only the first six are visible, but when you click on page 2 or next, the next six are revealed et cetera. The class of the page number you are on should also be set to have class="current".

    So far I have tried using jQuery, but I have been getting quite stuck! Any help would be much appreciated!

  • Benjamin
    Benjamin almost 10 years
    Have a doubt why do u want use parseInt though u can show the text by using this.text()
  • Mark G.
    Mark G. over 9 years
    Any time you see code like $('.content').eq((page-1)*6).show().next().show().next().sho‌​w().next().show().ne‌​xt().show().next().s‌​how(); it's a candidate for using a loop. Just sayin'