Dynamic pagination in Jquery

Corentin Branquet picture Corentin Branquet · Aug 10, 2015 · Viewed 38.4k times · Source

I have this code :

Instead of writing numbers manually in my HTML file, I want the numbers generate automatically according to the number of divs to display.

The code I have works but there is nothing in page 3 and 4. Instead of update the numbers in my HTML file, I want them to change dynamically with Jquery

Answer

semirturgay picture semirturgay · Aug 10, 2015

calculate page count than via a loop create links to pages.

//Pagination
	pageSize = 8;

	var pageCount =  $(".line-content").length / pageSize;
    
     for(var i = 0 ; i<pageCount;i++){
        
       $("#pagin").append('<li><a href="#">'+(i+1)+'</a></li> ');
     }
        $("#pagin li").first().find("a").addClass("current")
    showPage = function(page) {
	    $(".line-content").hide();
	    $(".line-content").each(function(n) {
	        if (n >= pageSize * (page - 1) && n < pageSize * page)
	            $(this).show();
	    });        
	}
    
	showPage(1);

	$("#pagin li a").click(function() {
	    $("#pagin li a").removeClass("current");
	    $(this).addClass("current");
	    showPage(parseInt($(this).text())) 
	});
.current {
  color: green;
}

#pagin li {
  display: inline-block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="line-content">1 I have some content</div>
<div class="line-content">2 I have some content</div>
<div class="line-content">3 I have some content</div>
<div class="line-content">4 I have some content</div>
<div class="line-content">5 I have some content</div>
<div class="line-content">6 I have some content</div>
<div class="line-content">7 I have some content</div>
<div class="line-content">8 I have some content</div>
<div class="line-content">9 I have some content</div>
<div class="line-content">10 I have some content</div>
<div class="line-content">11 I have some content</div>
<div class="line-content">12 I have some content</div>

<ul id="pagin">
         
</ul>