Client Side pagination with jQuery

Posted by TheNone on Stack Overflow See other posts from Stack Overflow or by TheNone
Published on 2011-01-05T15:25:12Z Indexed on 2011/01/05 18:54 UTC
Read the original article Hit count: 127

Filed under:
|

I have tried to write a script for pagination contents of an element with jQuery:

<script type="text/javascript">
$(document).ready(function(){
    var per_page = 2; 
    var num_item = $('#en1').children().size();
    var num_page = Math.ceil(num_item/per_page);
    $('#current_page').val(0);
    $('#per_page').val(per_page);
    var navigation_html = '';
    var current = 0;
    while(num_page > current){
        navigation_html += '<a class="page_link" href="javascript:paginate(' + current +')" longdesc="' + current +'">'+ (current + 1) +'</a>';
        current++;
    }
    $('#page_navigation').html(navigation_html);
    $('#page_navigation .page_link:first').addClass('active_page');
    $('#en1').children().css('display', 'none');
    $('#en1').children().slice(0, per_page).css('display', 'block');

});


function paginate(page_num){
    var per_page = parseInt($('#per_page').val());
    start = page_num * per_page;
    finish= start + per_page;
    $('#en1').children().css('display', 'none').slice(start, finish).css('display', 'block');
    $('.page_link[longdesc=' + page_num +']').addClass('active_page').siblings('.active_page').removeClass('active_page');
    $('#current_page').val(page_num);
}
</script>

http://jsfiddle.net/kqfyL/9/

This script paginate the contents of element by id "en1". I want to paginate 4-5 element (en2, en3, ...). When I insert code inside o document ready in a function, pagination doesnt work:

function init(myId){
var ID = document.getElementById("myId");
var per_page = 6; 
var num_item = $(ID).children().size();
var num_page = Math.ceil(num_item/per_page);

$('#current_page').val(0);
$('#per_page').val(per_page);

var navigation_html = '';
var current = 0;
while(num_page > current){
    navigation_html += '<a class="page_link" href="javascript:paginate(' + current +')" longdesc="' + current +'">'+ (current + 1) +'</a>';
    current++;
}


$('#page_navigation').html(navigation_html);
$('#page_navigation .page_link:first').addClass('active_page');
$('#ID').children().css('display', 'none');
$('#ID').children().slice(0, per_page).css('display', 'block');

}

init(en1);

What is wrong in init function?

Thanks in advance

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about jQuery