Skip to content Skip to sidebar Skip to footer

Counting Divs For Pagination In Jquery

I want to create a nice pagination in Jquery for a number of divs I have. EG:
content

Solution 1:

Something like this:

// Get all immediate child divs and their countvar$divs = $('div.container > div');
var pages = $divs.length;

// Hide every one but the first$divs.not(':first').hide();

// Create a container for the pagination$ul = $('<ul />');

// Create links for pagination inside the ulfor(var i = 0; i < pages; i++) {
    $ul.append($('<li><a href="#" class="pagination" rel="'+i+'">'+i+'</a></li>'));
}

// Insert the pagination container
$('div.container').before($ul);

// Behaviour for clicking the links inside pagination container$ul.find('a.pagination').click(function() {
    // Get the index from current element's rel attributevar index = parseInt($(this).attr('rel'), 10);
    // Hide every div and show the div at the current index's location$divs.hide().eq(index).show();
    returnfalse;
});

Haven't tested that but it should give you starters. Basically it just creates an ul element which controls which divs show up.

Solution 2:

Use the .addClass() and .removeClass - just put a class on the first page (div) that shows, and all the others that hides, and swap them (hiding one with current visibility by adding the hide class and removing the show class, and the inverse for the new page you wish to show by adding/removing CSS classes.

Solution 3:

How about this?

// Opens a certain div in the .containerfunctionopenUpPage(id) {
        $('.container div').hide(); // hide all divs in container
        $('#'+id).show(); // show only this one
    }

    // Gets called on document load
    $(function() {
        var i = 0;
        $('.container div').each(function (){
            i++;
            $(this).hide(); // hide
            $('#paginator').append("<a href=\"javascript: openUpPage('"+$(this).attr('id')+"')\">"+i+"</a>|");
        });

    });

Note add this to your HTML where the pagination should go:

<div id="paginator">  </div>

Otherwise, there's lots of plugins that do this for you (such as tablesorter with tablesorter.paginated) or you can use jQuery UI tabs. Good luck!

Post a Comment for "Counting Divs For Pagination In Jquery"