1(818)262-8552
Or Email
contact@invertedsoftware.com

Javascript numeric paging


By Gal Ratner

Numeric paging is the most common way to navigate between records in a grid containing more than one page of data.
The navigating buttons are usually either handled by the grid build in paging function,
when we are using an ASP.NET GridView or custom code we write if we are using another control such as a Repeater or even working with custom code in ASP or PHP.
In any case, the code resides on the server and can cause some overhead on high traffic pages.

Here is a little script I developed. It takes the paging responsibility off the server and passes it on to the client using Javascript.
The server side code simply invokes a javascript function call on every page request in order to display the correct navigation for that page.

Invoking the script looks like:

showPager(currentPage, pageSize, totalRecords, totalPages)
currentPage: Is a query string request from the Page variable the script sends back as a link.
pageSize: the size of the page you wish to display
totalRecords: will come from your server side code
totalPages: will also come from your server side code. It can be easily calculated in the Javascript, however, I found that most server side code already has this calculated so there is no need to recalculate and we simply pass it on to the function call

Where in my page will the pager be painted?

You need to define a div with the ID PagerDiv
<div id="PagerDiv"></div>
function showPager(currentPage, pageSize, totalRecords, totalPages){
 var linkToPage = "... ";
	
 // Dispaly 4 pages before and 4 pages after the current page
 var linksGenerated = 0;
 var lastLinkGenerated = 0;
 for(var i = (currentPage - 4); i < (currentPage + 4); i++){
  if(i < totalPages && i >= 0){ // If the page exist show a link to it	
			
   if(i == currentPage) pagerHTML += "" + linkToPage + i + pageParameters + "'>"
    + (i + 1) + " ";
	else
	 pagerHTML += linkToPage + i + pageParameters + "'>" + (i + 1) + " ";
	linksGenerated++;
	lastLinkGenerated = i;
	}
}
	
//Complete any missing pages
 for(var i = 1; i <= (9 - linksGenerated); i++){
  if(lastLinkGenerated < (totalPages - 1)){
   lastLinkGenerated++;
   pagerHTML += linkToPage + lastLinkGenerated + pageParameters + "'>"
   + (lastLinkGenerated + 1) + " ";
  }
 }
	
 if(currentPage < totalPages - 1)
  pagerHTML += linkToPage + (totalPages - 1) + pageParameters +"'>...";

  document.getElementById("PagerDiv").innerHTML = pagerHTML;
}

function getPageParams(){
 var regexPage = new RegExp( "[?&]Page=([^&$]*)");
 var pageParameters = document.location.search.replace(regexPage, "");
 return pageParameters.replace('?', '&');
}


The result looks like this:



Point to remember: Please call the script after PagerDiv has been loaded
You can download the JS file here.
Happy Coding!


About Us | Contact Us | Standards of Business Conduct | Employment
InvertedSoftware.com All rights reserved