first of all, to be clear i am a newbie with javascript and jquery.
now, i am using a javascript file to paginate inside a div. the script works fine, but if there is a lot of data then i need to limit the paginating links with a "next" and a "previous" tag. i can't find a way to do that. currently the pagination script is showing all the numbers like 1 2 3 4 5 6 7 8 9 etc depending on the data supplied. but, i want to show them like, 1 2 3 4 5 next>> or, <<prev 2 3 4 5 6 next>>
here is my pagination.js
var Imtech = {};
Imtech.Pager = function() {
this.paragraphsPerPage = 3;
this.currentPage = 1;
this.pagingControlsContainer = "#pagingControls";
this.pagingContainerPath = "#content";
this.numPages = function() {
var numPages = 0;
if (this.paragraphs != null && this.paragraphsPerPage != null) {
numPages = Math.ceil(this.paragraphs.length / this.paragraphsPerPage);
}
return numPages;
};
this.showPage = function(page) {
this.currentPage = page;
var html = "";
for (var i = (page-1)*this.paragraphsPerPage; i < ((page-1)*this.paragraphsPerPage) + this.paragraphsPerPage; i++) {
if (i < this.paragraphs.length) {
var elem = this.paragraphs.get(i);
html += "<" + elem.tagName + ">" + elem.innerHTML + "</" + elem.tagName + ">";
}
}
$(this.pagingContainerPath).html(html);
renderControls(this.pagingControlsContainer, this.currentPage, this.numPages());
}
var renderControls = function(container, currentPage, numPages) {
var pagingControls = "<b>Pages</b>: <ul>";
for (var i = 1; i <= numPages; i++) {
if (i != currentPage) {
pagingControls += "<li><a href='#' onclick='pager.showPage(" + i + "); return false;'>" + i + "</a></li>";
} else {
pagingControls += "<li>" + i + "</li>";
}
}
pagingControls += "</ul>";
$(container).html(pagingControls);
}
}
to get the desired look, how do i edit this script?if anyone could help me with it, please do so.
You could change renderControls like this:
var renderControls = function(container, currentPage, numPages, pagesCutoff) {
var pagingControls = "<b>Pages</b>: <ul>";
var prevPosition = currentPage - pagesCutoff;
var nextPosition = currentPage + pagesCutoff;
for (var i = 1; i <= numPages; i++) {
if (i != currentPage) {
if(i >= prevPosition && i <= nextPosition) {
var linkToPage = i == prevPosition ? currentPage - 1 : i == nextPosition ? currentPage + 1 : i;
var linkText = i == prevPosition ? "<< prev" : i == nextPosition ? "next >>" : i;
pagingControls += "<li><a href='#' onclick='pager.showPage(" + linkToPage + "); return false;'>" + linkText + "</a></li>";
}
} else {
pagingControls += "<li>" + i + "</li>";
}
}
pagingControls += "</ul>";
$(container).html(pagingControls);
}
And add this to Imtech.Pager: this.pageLinksEachSide = 3;
And change the renderControls call to this: renderControls(this.pagingControlsContainer, this.currentPage, this.numPages(), this.pageLinksEachSide);
This is assuming that you want the "next" link to navigate to currentPage + 1 and the "prev" link to navigate to currentPage - 1.
Related
I am using the script below to show the latest 5 posts on my Blogger blog. How can I wrap the first and last 2 posts in different div containers? Currently all the 5 posts are inside a wrapper container stored in the item variable:
<script type='text/javascript'>
function mycallback(json) {
for (var i = 0; i < json.feed.entry.length; i++) {
for (var j = 0; j < json.feed.entry[i].link.length; j++) {
if (json.feed.entry[i].link[j].rel == 'alternate') {
var postUrl = json.feed.entry[i].link[j].href;
break;
}
}
var postTitle = json.feed.entry[i].title.$t;
var postAuthor = json.feed.entry[i].author[0].name.$t;
var postSummary = json.feed.entry[i].summary.$t;
var entryShort = postSummary.substring(0,400);
var entryEnd = entryShort.lastIndexOf(" ");
var postContent = entryShort.substring(0, entryEnd) + '...';
var postImage = json.feed.entry[i].media$thumbnail.url.replace('s72-c/','s1600/');
var item = '<div class="wrapper"><img src="' + postImage + '"/><h3><a href=' + postUrl + '>' + postTitle + '</h3></a><span>'+ postAuthor + '</span><p>' + postContent + '</p></div>';
document.write(item);
}
}
</script>
<script src="/feeds/posts/summary?orderby=published&max-results=5&alt=json-in-script&callback=mycallback"></script>
More generic solution would not check for last and previous to last elements checking for 3 or 4 but should be based on total length of your posts (it can be 3 it can be 10000).
Checks below should be place in your loop.
if(i === 0 || i === 1)
Always use === operator as it is typesafe.
Also group your checks in a way that is easy to understand (check for first and second in one if and for last and previous to last in another if:
if(i === json.feed.entry.length || i === json.feed.entry.length - 1) - this check is based on length of your entries, not some fixed value like 3 or 4.
This way if your displayed entries value will change in future (to ex. 10), you don't need to adjust your code here. All code you write should strive to work without such adjustments when code it uses changes.
Check desired elements through loop
// to check first or fourth element
if (i == 0 || i == 3)
// to check second or fifth element
if (i == 1 || i == 4)
Wrap them by adding HTML tages
<script type='text/javascript'>
function mycallback(json) {
for (var i = 0; i < json.feed.entry.length; i++) {
for (var j = 0; j < json.feed.entry[i].link.length; j++) {
if (json.feed.entry[i].link[j].rel == 'alternate') {
var postUrl = json.feed.entry[i].link[j].href;
break;
}
}
var postTitle = json.feed.entry[i].title.$t;
var postAuthor = json.feed.entry[i].author[0].name.$t;
var postSummary = json.feed.entry[i].summary.$t;
var entryShort = postSummary.substring(0,400);
var entryEnd = entryShort.lastIndexOf(" ");
var postContent = entryShort.substring(0, entryEnd) + '...';
var postImage = json.feed.entry[i].media$thumbnail.url.replace('s72-c/','s1600/');
var item = '<div class="wrapper"><img src="' + postImage + '"/><h3><a href=' + postUrl + '>' + postTitle + '</h3></a><span>'+ postAuthor + '</span><p>' + postContent + '</p></div>';
if (i == 0 || i == 3) document.write('<div>');
document.write(item);
if (i == 1 || i == 4) document.write('</div>');
}
}
</script>
<script src="/feeds/posts/summary?orderby=published&max-results=5&alt=json-in-script&callback=mycallback"></script>
I want to create dots in breadcrumb if they exceeds some specific limit of numbers. I added script, to create breadcrumb but it's not working.
I am stuck where i have to add dots so that when bread crumb item exceeds it hides and create dots
function getBreadCrumb() {
if (window.ActiveTab != 'local') {
$('#fr-h-r-3 .breadcrumb.fr-breadcrumb').html('');
return false
}
/*alert(window.ActiveTab);
if(window.ActiveTab == 'fb'){
$('#fr-h-r-3 .breadcrumb.fr-breadcrumb').html('<li>Facebook-Images</li>');
return false;
}else if(window.ActiveTab == 'ig'){
$('#fr-h-r-3 .breadcrumb.fr-breadcrumb').html('<li>Instagram-Images</li>');
return false
}*/
var currentPath = b.opts.userFolderDefaultPath;
if (b.opts.imageManagerFolders.length > 0) {
currentPath = b.opts.userFolderDefaultPath + b.opts.imageManagerFolders.join('/') + '/';
}
var sArray = currentPath.split('/');
var fArray = currentPath.split('/');
fArray.pop();
fArray.shift();
sArray.shift();
sArray.shift();
sArray.shift();
sArray.pop();
var html = '<li><span class="fa fa-home"></span></li>';
/*console.log('sArray: '+sArray);
console.log('fArray: '+fArray);*/
function getPath(i) {
var hisPath = '';
for (var j = 2; j < (i + 3); j++) {
if (fArray[j] != 'undefined') {
hisPath += fArray[j] + '/';
}
}
return hisPath;
}
if (sArray.length > 6) {
as = 4;
al = (sArray.length - 3)
}
sts = false;
for (var i = 0; i < sArray.length; i++) {
if ((i + 1) != sArray.length) {
if (typeof as != 'undefined' && i == as) {
sts = true;
}
if (typeof al != 'undefined' && i == al) sts = false;
if (sts == false) {
html += '<li><a onClick="$(document).trigger(\'ImageManager.LoadBreadCrumbFolder\',[this]);" href="javascript:void(0);" data-name="' + sArray[i] + '" data-hist="' + getPath(i) + '" data-path="/' + fArray[0] + '/' + fArray[1] + '/' + getPath(i) + '">' + sArray[i] + '</a></li>';
}
} else {
html += '<li class="active">' + sArray[i] + '</li>';
}
//html += '<li class="active">'+sArray[i]+'</li>';
}
$('#fr-h-r-3 .breadcrumb.fr-breadcrumb').html(html);
}
Thank you for your efforts, i was working on this, i solved this by only adding this code into function.
if(typeof as != 'undefined' && i==as) { sts = true; html += '<li>...</li>'; }
where the line is
if (typeof as != 'undefined' && i == as) {
sts = true;
}
this script is generating a pagination you can see in script. and the final output is this.
simple pagination without dots.
checkttttNew-Folder-1New-Folder-1New-Folder-1
when exceeds 6 li then it creates dots. like this.
checkttttNew-Folder-1New-Folder-1...New-Folder-1htesttes2
I am displaying pagination in my application using following javascript,its working fine for me, but i need to break the pagination after 5 pages
This is my existing pagination
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
but i need to display the pagination by following
1 2 3 4 5 ......15 16 17 18 19 20
if i click on page number 5 then it should add another 5 pages to current page
My Javscript like this
<script type="text/javascript">
function Pager(tableName, itemsPerPage) {
this.tableName = tableName;
this.itemsPerPage = itemsPerPage;
this.currentPage = 1;
this.pages = 0;
this.inited = false;
this.showRecords = function(from, to) {
var rows = document.getElementById(tableName).rows;
// i starts from 1 to skip table header row
for (var i = 1; i < rows.length; i++) {
if (i < from || i > to)
rows[i].style.display = 'none';
else
rows[i].style.display = '';
}
}
this.showPage = function(pageNumber) {
if (! this.inited) {
alert("not inited");
return;
}
var oldPageAnchor = document.getElementById('pg'+this.currentPage);
oldPageAnchor.className = 'pg-normal';
this.currentPage = pageNumber;
var newPageAnchor = document.getElementById('pg'+this.currentPage);
newPageAnchor.className = 'pg-selected';
var from = (pageNumber - 1) * itemsPerPage + 1;
var to = from + itemsPerPage - 1;
this.showRecords(from, to);
}
this.prev = function() {
if (this.currentPage > 1)
this.showPage(this.currentPage - 1);
}
this.next = function() {
if (this.currentPage < this.pages) {
this.showPage(this.currentPage + 1);
}
}
this.init = function() {
var rows = document.getElementById(tableName).rows;
var records = (rows.length - 1);
this.pages = Math.ceil(records / itemsPerPage);
this.inited = true;
}
this.showPageNav = function(pagerName, positionId) {
if (! this.inited) {
alert("not inited");
return;
}
var element = document.getElementById(positionId);
var pagerHtml = '<span onclick="' + pagerName + '.prev();" class="pg-normal"> <img src="${ctx}/images/prev.PNG" alt=" « Prev" height="17px" width="26px" style="vertical-align: middle;"/> </span> ';
for (var page = 1; page <= this.pages; page++)
pagerHtml += '<span id="pg' + page + '" class="pg-normal" onclick="' + pagerName + '.showPage(' + page + ');">' + page + '</span> ';
pagerHtml += '<span onclick="'+pagerName+'.next();" class="pg-normal"> <img src="${ctx}/images/nexts.png" alt="Next »" height="17px" width="26px" style="vertical-align: middle;"/></span>';
element.innerHTML = pagerHtml;
}
}
</script>
if any suggestion it will be appreciable
here is the JSfiddle
Here is a new jsfiddle doing what you want to do:
http://jsfiddle.net/nye7a/2/
The showPageNav function has been changed like this :
this.showPageNav = function(pagerName, positionId) {
var pageIndex = this.currentPage,
pageCount = this.pages,
start = Math.max(1, pageIndex - 4),
end = Math.min(pageCount, pageIndex + 4),
start2 = pageCount-4,
end2 = pageCount;
if (start2 <= end)
end = pageCount;
if (! this.inited) {
alert("not inited");
return;
}
var element = document.getElementById(positionId);
var pagerHtml = '';
// adds the Prev button only if needed
if (pageIndex > 1)
pagerHtml = '<span onclick="' + pagerName + '.prev();" class="pg-normal"> « Prev </span> ';
// paging from 1 to 5
for (var page = start; page <= end; page++) {
pagerHtml += '<span id="pg' + page + '" class="pg-normal" onclick="' + pagerName + '.showPage(' + page + ');">' + page + '</span> ';
}
// paging from pageCount-5 to pageCount
if (end != pageCount) {
pagerHtml += '<span>...</span>';
for (var page = start2; page <= end2; page++) {
pagerHtml += '<span id="pg' + page + '" class="pg-normal" onclick="' + pagerName + '.showPage(' + page + ');">' + page + '</span> ';
}
}
// adds the Next button only if needed
if (pageIndex < pageCount && pageCount > 1)
pagerHtml += '<span onclick="'+pagerName+'.next();" class="pg-normal"> Next »</span>';
element.innerHTML = pagerHtml;
}
i have this .js file for the pagination in html anybody can help me what i have to change to show the different url for each page & user can save that url & can use it for future use to go on that specific page.
(.js file start from below)
function Pager(tableName, itemsPerPage) {
this.tableName = tableName;
this.itemsPerPage = itemsPerPage;
this.currentPage = 1;
this.pages = 0;
this.inited = false;
this.showRecords = function(from, to) {
var rows = document.getElementById(tableName).rows;
// i starts from 1 to skip table header row
for (var i = 1; i < rows.length; i++) {
if (i < from || i > to)
rows[i].style.display = 'none';
else
rows[i].style.display = '';
}
}
this.showPage = function(pageNumber) {
if (! this.inited) {
alert("not inited");
return;
}
var oldPageAnchor = document.getElementById('pg'+this.currentPage);
oldPageAnchor.className = 'pg-normal';
this.currentPage = pageNumber;
var newPageAnchor = document.getElementById('pg'+this.currentPage);
newPageAnchor.className = 'pg-selected';
var from = (pageNumber - 1) * itemsPerPage + 1;
var to = from + itemsPerPage - 1;
this.showRecords(from, to);
}
this.prev = function() {
if (this.currentPage > 1)
this.showPage(this.currentPage - 1);
}
this.next = function() {
if (this.currentPage < this.pages) {
this.showPage(this.currentPage + 1);
}
}
this.init = function() {
var rows = document.getElementById(tableName).rows;
var records = (rows.length - 1);
this.pages = Math.ceil(records / itemsPerPage);
this.inited = true;
}
this.showPageNav = function(pagerName, positionId) {
if (! this.inited) {
alert("not inited");
return;
}
var element = document.getElementById(positionId);
var pagerHtml = '<span onclick="' + pagerName + '.prev();" class="pg-normal"> « Prev </span> | ';
for (var page = 1; page <= this.pages; page++)
pagerHtml += '<span id="pg' + page + '" class="pg-normal" onclick="' + pagerName + '.showPage(' + page + ');">' + page + '</span> | ';
pagerHtml += '<span onclick="'+pagerName+'.next();" class="pg-normal"> Next »</span>';
element.innerHTML = pagerHtml;
}
}
in this.showPage() update the url hash with something like "pg=1":
location.hash = "#pg=" + pageNumber;
That method will add an item to your page history. If you don't want to add an item to your page history, use this:
location.replace("#pg=" + pageNumber);
Then, when the page is loaded, after you call pager.init(), you'll want to call pager.showPage(). You can use this code to decide whether to load the first page or the page from the url::
var page = /\bpg=(\d+)\b/.test(location.hash) ? parseInt(RegExp.$1) : 1;
pager.showPage(page);
Could anyone suggest performance improvements for the function I've written (below, javascript with bits of jquery)? Or point out any glaring, basic flaws? Essentially I have a javascript Google map and a set of list based results too, and the function is fired by a checkbox click, which looks at the selection of checkboxes (each identifying a 'filter') and whittles the array data down accordingly, altering the DOM and updating the Google map markers according to that. There's a 'fake' loader image in there too at the mo that's just on a delay so that it animates before the UI hangs!
function updateFilters(currentCheck) {
if (currentCheck == undefined || (currentCheck != undefined && currentCheck.disabled == false)) {
var delay = 0;
if(document.getElementById('loader').style.display == 'none') {
$('#loader').css('display', 'block');
delay = 750;
}
$('#loader').delay(delay).hide(0, function(){
if (markers.length > 0) {
clearMarkers();
}
var filters = document.aspnetForm.filters;
var markerDataArray = [];
var filterCount = 0;
var currentfilters = '';
var infoWindow = new google.maps.InfoWindow({});
for (i = 0; i < filters.length; i++) {
var currentFilter = filters[i];
if (currentFilter.checked == true) {
var filtername;
if (currentFilter.parentNode.getElementsByTagName('a')[0].textContent != undefined) {
filtername = currentFilter.parentNode.getElementsByTagName('a')[0].textContent;
} else {
filtername = currentFilter.parentNode.getElementsByTagName('a')[0].innerText;
}
currentfilters += '<li>' + $.trim(filtername) +
$.trim(document.getElementById('remhide').innerHTML).replace('#"','#" onclick="toggleCheck(\'' + currentFilter.id + '\');return false;"');
var nextFilterArray = [];
filterCount++;
for (k = 0; k < filterinfo.length; k++) {
var filtertype = filterinfo[k][0];
if (filterinfo[k][0] == currentFilter.id) {
var sitearray = filterinfo[k][1];
for (m = 0; m < sitearray.length; m++) {
var thissite = sitearray[m].split(',');
if (filterCount > 1) {
nextFilterArray.push(thissite[2] + '|' + thissite[1]
+ '|' + thissite[0]);
} else {
markerDataArray.push(thissite[2] + '|' + thissite[1]
+ '|' + thissite[0]);
}
}
}
}
if (filterCount > 1) {
var itemsToRemove = [];
for (j = 0; j < markerDataArray.length; j++) {
var exists = false;
for (k = 0; k < nextFilterArray.length; k++) {
if (markerDataArray[j] == nextFilterArray[k]) {
exists = true;
}
}
if (exists == false) {
itemsToRemove.push(j);
}
}
var itemsRemoved = 0;
for (j = 0; j < itemsToRemove.length; j++) {
markerDataArray.splice(itemsToRemove[j]-itemsRemoved,1);
itemsRemoved++;
}
}
}
}
if (currentfilters != '') {
document.getElementById('appliedfilters').innerHTML = currentfilters;
document.getElementById('currentfilters').style.display = 'block';
} else {
document.getElementById('currentfilters').style.display = 'none';
}
if (filterCount < 1) {
for (j = 0; j < filterinfo.length; j++) {
var filtertype = filterinfo[j][0];
if (filterinfo[j][0] == 'allvalidsites') {
var sitearray = filterinfo[j][1];
for (m = 0; m < sitearray.length; m++) {
var thissite = sitearray[m].split(',');
markerDataArray.push(thissite[2] + '|' + thissite[1]
+ '|' + thissite[0]);
}
}
}
}
var infoWindow = new google.maps.InfoWindow({});
var resultHTML = '<div id="page1" class="page"><ul>';
var count = 0;
var page = 1;
var paging = '<li class="selected">1</li>';
for (i = 0; i < markerDataArray.length; i++) {
var markerInfArray = markerDataArray[i].split('|');
var url = '';
var name = '';
var placename = '';
var region = '';
var summaryimage = 'images/controls/placeholder.gif';
var summary = '';
var flag = 'images/controls/placeholderf.gif';
for (j = 0; j < tsiteinfo.length; j++) {
var thissite = tsiteinfo[j].split('|');
if (thissite[0] == markerInfArray[2]) {
name = thissite[1];
placename = thissite[2];
region = thissite[3];
if (thissite[4] != '') {
summaryimage = thissite[4];
}
summary = thissite[5];
if (thissite[6] != '') {
flag = thissite[6];
}
}
}
for (k = 0; k < sitemapperinfo.length; k++) {
var thissite = sitemapperinfo[k].split('|');
if (thissite[0] == markerInfArray[2]) {
url = thissite[1];
}
}
var markerLatLng = new google.maps.LatLng(markerInfArray[1].toString(), markerInfArray[0].toString());
var infoWindowContent = '<div class="infowindow">' + markerInfArray[2] + ': ';
var siteurl = approot + '/sites/' + url;
infoWindowContent += '<strong>' + name + '</strong>';
infoWindowContent += '<br /><br/><em>' + placename + ', ' + region + '</em></div>';
marker = new google.maps.Marker({
position: markerLatLng,
title: $("<div/>").html(name).text(),
shadow: shadow,
icon: image
});
addInfo(infoWindow, marker, infoWindowContent);
markers.push(marker);
count++;
if ((count > 20) && ((count % 20) == 1)) { // 20 per page
page++;
resultHTML += '</ul></div><div id="page' + page + '" class="page"><ul>';
paging += '<li>' + page + '</li>';
}
resultHTML += '<li><div class="namehead"><h2>' + name + ' <span>' + placename + ', ' + region + '</span></h2></div>' +
'<div class="codehead"><h2><img alt="' + region + '" src="' + approot +
'/' + flag + '" /> ' + markerInfArray[2] + '</h2></div>' +
'<div class="resultcontent"><img alt="' + name + '" src="' + approot +
'/' + summaryimage +'" />' + '<p>' + summary + '</p>' + document.getElementById('buttonhide').innerHTML.replace('#',siteurl) + '</div></li>';
}
$('#filteredmap .paging').each(function(){
$(this).html(paging);
});
document.getElementById('resultslist').innerHTML = resultHTML + '</ul></div>';
document.getElementById('count').innerHTML = count + ' ';
document.getElementById('page1').style.display = 'block';
for (t = 0; t < markers.length; t++) {
markers[t].setMap(filteredMap);
}
});
}
}
function clearMarkers() {
for (i = 0; i < markers.length; i++) {
markers[i].setMap(null);
markers[i] = null;
}
markers.length = 0;
}
However, I'm suffering from performance issues (UI hanging) specifically in IE6 and 7 when the number of results is high, but not in any other modern browsers, i.e. FF, Chrome, Safari etc. It is much worse when the Google map markers are being created and added (if I remove this portion it is still slugglish, but not to the same degree). Can you suggest where I'm going wrong with this?
Thanks in advance :) Please be gentle if you can, I don't do much javascript work and I'm pretty new to it and jquery!
This looks like a lot of work to do at the client no matter what.
Why don't you do this at the server instead, constructing all the HTML there, and just refresh the relevant sections with the results of an ajax query?