Syed Priom Syed Priom - 1 month ago 14
Javascript Question

Using Bootstrap to paginate a set number of <p> elements on a webpage

The application I work with serves 'article pages' consisting of many paragraphs using

<p>
element, now I want to paginate these paragraphs, suppose 15 paragraphs in three pages, with 5 paragraphs in each page.

What the Bootstrap tutorial explains is based on list elements, I am sure there must have been a way to implement this for other elements?

I came across another good plugin called Pajinate, but it requires list elements explicitly!

Does Bootstrap or any plug in out there offers a solution where we can apply pagination based on any specific HTML element or CSS class? My problem is to find one that I can apply to
<p>
element.

Answer

Rather than using a jquery plugin or server-side paging you can make a fairly simple paging implementation for Bootstrap using jQuery and the Bootstrap pagination class..

var listElement = $('#pageStuff');
var perPage = 2; 
var numItems = listElement.children().size();
var numPages = Math.ceil(numItems/perPage);

$('.pager').data("curr",0);

var curr = 0;
while(numPages > curr){
  $('<li><a href="#" class="page_link">'+(curr+1)+'</a></li>').appendTo('.pager');
  curr++;
}

$('.pager .page_link:first').addClass('active');

listElement.children().css('display', 'none');
listElement.children().slice(0, perPage).css('display', 'block');

$('.pager li a').click(function(){
  var clickedPage = $(this).html().valueOf() - 1;
  goTo(clickedPage,perPage);
});

function previous(){
  var goToPage = parseInt($('.pager').data("curr")) - 1;
  if($('.active').prev('.page_link').length==true){
    goTo(goToPage);
  }
}

function next(){
  goToPage = parseInt($('.pager').data("curr")) + 1;
  if($('.active_page').next('.page_link').length==true){
    goTo(goToPage);
  }
}

function goTo(page){
  var startAt = page * perPage,
    endOn = startAt + perPage;

  listElement.children().css('display','none').slice(startAt, endOn).css('display','block');
  $('.pager').attr("curr",page);
}

Place all of the paragraphs in one container, and id the container as 'listStuff'.

Just change the var perPage = 2 to whatever you want (ie: 5).

Working demo: http://bootply.com/66815