I am working on pulling in objects from a JSON file and placing them into a masonry-like grid using Salvattore. I found this tutorial which worked great for pulling in the data but now I would like to set up a pagination system. Currently I have it working so that on initial load only 6 objects are returned and populated, but I am not sure how to program the "load more" button so that it appends only the next 6 posts.
Here is what I have so far:
function getResults(filter) {
$.getJSON("results.json", function(data) {
var perPage = 6;
var count = data.posts.length;
$(data.posts).each(function (i, post) {
if (filter) {
if (post.source === filter && i < perPage) {
populate(post.source, post.permalink, post.content, post.date);
}
} else if(i < perPage) {
populate(post.source, post.permalink, post.content, post.date);
}
i = i + 6;
});
perPage = perPage + 6;
});
}
getResults();
I'm not entirely sure what the logic should be to set this up so I am just guess/checking right now. If anyone could point me in the right direction it would be greatly appreciated.
Here is a Plunker which has the HTML/Sample JSON and the rest of my JavaScript.
If you are going to send data to your back-end, you'll need to send the page. You can do like this:
var currentPage = 1;
function getResults(filter, page) {
$.ajax({
dataType: "json",
url: url,
data: {page: currentPage},
success: function(data) { ... code here ... }
});
}
$('.load-more').click(function(e) {
currentPage++;
getResults();
});
But, if you're goin to show data from a JSON, the browser will download entire JSON in the beginning, so you already have the data, then you can do this:
var currentPage = 1;
$('.load-more').click(function(e) {
currentPage++;
getResults();
});
function getResults(filter) {
$.getJSON("results.json", function(data) {
var perPage = 6;
var count = data.posts.length;
if((currentPage-1) * perPage > count)
alert("all pages fetched");
return false;
}
$(data.posts).each(function (i, post) {
if(i >= (currentPage -1) * perPage && i < currentPage * perPage) {
if (filter) {
if(post.source === filter) {
populate(post.source, post.permalink, post.content, post.date);
}
} else {
populate(post.source, post.permalink, post.content, post.date);
}
i = i + perPage;
}
});
perPage += perPage;
});
}
I've forked your plunker here: https://plnkr.co/edit/7kn2n9uhBPGZxXDLPLIz?p=preview
There is still one problem, the append function isn't working properly, but maybe it's a bug in your library or the way you are using it.
Related
`Hello,
I want to implement infinite scrolling in hands on table in my project.
when i scroll down in table, it add next page but when i scroll up it doesen't show previous page and when i reached at last page then scrollbar was disappear and i stuck to the last page.
This is js file.
var position = $('.wtHolder').scrollTop();
var total_pages = <%= #sp_data.total_pages %>;
console.log( 'total', total_pages)
$('.wtHolder').scroll(function(){
var scr = $('.wtHolder').scrollTop();
if ((scr >= 120 ) && page < total_pages) {
page++;
appendHOT2();
hot.updateSettings({ mergeCells: merge()})
}
if ($(this).scrollTop() + $(this).innerHeight() >= $(this)[0].scrollHeight && page < total_pages) {
$(this).scrollTop($(".wtHolder").scrollTop() - 25);
console.log('page' , page)
}
});
function appendHOT2() {
// debugger;
var hotData = hot.getData();
// console.log('more data', moreData(page) )
Array.prototype.push.apply(hotData, loadData(page));
hot.loadData(hotData);
console.log(page)
}
function merge() {
var mergeCells=[], rowspan=1, tempName = '';
for(var i=1; i<hot.getData().length; i++) {
// debugger
if (hot.getDataAtCell(i,1) === tempName) {
rowspan+=1;
}
else {
mergeCells.push({row:i-rowspan, col:0, rowspan:rowspan, colspan:1})
mergeCells.push({row:i-rowspan, col:1, rowspan:rowspan, colspan:1})
rowspan=1
}
tempName = hot.getDataAtCell(i,1);
}
return mergeCells;
}
function loadData(page) {
$.ajax({
url: `/surplus_data/index_datatable?page=${page}`,
type: 'get',
dataType: 'json',
async: true,
success: function(res) {
hot.loadData(res);
}
});
}
if(page==1){
loadData(page);
}```
in this, per page 50 records shown.
In my code I am retrieved data from the data base every 30 seconds using AJAX. I want to use JavaScript to increment variable wht every time data is received from the database (every 30 seconds) and when if statement is true. Below code is working and incrementing to 1 but it doesn't go above 1. Does anyone has a solution for this problem?
<script>
$(document).ready(function () {
ajax_call = function() {
$.ajax({
type: "GET",
url: "test.php",
dataType: "html",
success: function (response) {
color = response;
console.log(color);
if (color == white){
var wht = (function(w) {
return function() {
w += 1;
return w;
}
}(0));
document.getElementById("memo").value = wht();
}else{
console.log("Color is not white");
}
var interval = 30000;
setInterval(ajax_call, interval);
});
</script>
<script>
const minusButtonFw = document.getElementById('memo-minus');
const plusButtonFw = document.getElementById('memo-plus');
var memo = document.getElementById('memo');
minusButtonFw.addEventListener('click', event => {
event.preventDefault();
const currentValue = Number(memo.value);
memo.value = currentValue - 1;
});
plusButtonFw.addEventListener('click', event => {
event.preventDefault();
const currentValue = Number(memo.value);
memo.value = currentValue + 1;
});
</script>
First of all your variable wht is a function. If you simply want to keep track of the number of time the if conditions is true you can do it by making the variable static (literaly). you can achive this by storing the variable in a global scope.
Also there are sytax errors in your code too where wht is defined.
try this
$(function () {
var memo = document.getElementById("memo");
memo.val = 0;
var ajax_call = function () {
$.ajax({
type: "GET",
url: "test.php",
dataType: "html",
success: function (response) {
color = response;
console.log(color);
if (color == white) {
memo.val++;
memo.value = memo.val;
} else {
console.log("Color is not white");
}
}
});
}
var interval = 30000;
setInterval(ajax_call, interval);
});
A Note:
If the response is managed by you, I would recomend sending the response as json rather than simply sending it as an html with just one value color.
You'll need to keep track of "w". Your current setup is using "w" as a parameter to a function. You'd need to keep it outside of the function and increment it from inside the function. You'll also need to wrap that function in an interval Something like the following:
var w = 0;
function setWhite(color) {
if (color == white) {
w++;
document.getElementById("memo").value = w;
} else {
console.log("Color is not white");
}
}
setInterval(function() {
setWhite(color);
}, 30000);
This should give you what you want. I didn't run the code so there are probably syntactical errors that you'll need to correct.
Try change the line
document.getElementById("memo").value = wht();
to
document.getElementById("memo").value = wht(document.getElementById("memo").value);
Your full code:
<script>
$(document).ready(function () {
ajax_call = function() {
$.ajax({
type: "GET",
url: "test.php",
dataType: "html",
success: function (response) {
color = response;
console.log(color);
if (color == white){
var wht = (function(w) {
return function() {
w += 1;
return w;
}
}(0));
document.getElementById("memo").value = wht(document.getElementById("memo").value);
}else{
console.log("Color is not white");
}
var interval = 30000;
setInterval(ajax_call, interval);
});
</script>
I made an example with setInterval. I made w global so it will work. Try this:
var w = 0;
var interval = setInterval(function() {
if (color == white) {
w++;
document.getElementById("memo").value = w;
} else {
console.log("Color is not white");
}
}, 30000);
I would like to delay the for loop process so that the loading of data looks like a progress bar.
In this code, the moment i click the button, it will directly display this data: 20/20 Records Rendered.
I would like to see the record start with 1/20 Records Rendered then after 3 seconds it will become 2/20 Records Rendered and so on.
Here is the code:
<button name="subject" type="submit" value="6" onClick="Run(this.value)">Run</button>
<script>
function Run(value) {
custRecordsRendered = 0;
$.ajax({
type: 'Post',
url: "/Tasks/RunSample",
success: function (data) {
totalRecords = data[0].Total;
console.log("Total: " + data[0].Total);
console.log("Records: " + Object.keys(data).length);
for (var key in data) {
(function iterator() {
console.log("logs: "+data[key].Records);
setTimeout(iterator, 3000);
})();
if (data.hasOwnProperty(key)) {
custRecordsRendered = data[key].Records;
updateProgress();
}
}
}
});
function updateProgress() {
$("#completeCount").text(custRecordsRendered + "/" + totalRecords + " Records Rendered");
}
}
</script>
Controller:
public JsonResult RunSample()
{
List<object> countData = new List<object>();
int count = 20;
for (int i = 1; i <= count; i++)
{
countData.Add(new { Total = count, Records = i });
}
return Json(countData);
}
Thank you for helping me.
if I got what you mean correctly .. this code may do the trick
function Run(value) {
custRecordsRendered = 0;
$.ajax({
type: 'Post',
url: "/Home/RunSample",
success: function (data) {
totalRecords = data[0].Total;
console.log("Total: " + data[0].Total);
console.log("Records: " + Object.keys(data).length);
var itemCount = 0;
var progressInterval = setInterval(function () {
if (itemCount < data.length) {
console.log(itemCount);
console.log("logs: " + data[itemCount].Records);
custRecordsRendered = data[itemCount].Records;
updateProgress();
itemCount++;
}
else {
clearInterval(progressInterval);
}
}, 500);
}
});
function updateProgress() {
$("#completeCount").text(custRecordsRendered + "/" + totalRecords + " Records Rendered");
}
}
in your code you are treating the setTimeout function as if it causes the Thread to sleep but actually, it does not what it does is setting a delayed asynchronous event that will be fired after the specified interval and execute the handler function, but the execution of the code which is after the setTimeout call will continue .. so setInterval will serve the purpose for you
What I Need
i Need Like when user refesh page i need increment the count of session variable.
js code
<script type="text/javascript">
var count=0;
var counter=sessionStorage.setItem("count", 0);
var counters= sessionStorage.getItem("count");
console.log(counters);
var page_count =counters;
if (page_count == 4)
{
dataLayer.push({'event':'mobilePromo-android'});
}
$(document).ready(function()
{
var page_count =counters;
var height= $(window).height();
if (page_count == 4 )
{
$.ajax({
type: "GET",
url: "http://domain.com/mobilepopuptracker?from=android",
});
$('body').html('<div class="row flush aligncenter popbx" style="height:'+height+'px"><img src="http://im.gifbt.com/images/logo-300p");
}
else
{
}
counters=counters+1;
});
function redirect()
{
var a=$(location).attr('href');
window.location.href=a;
}
</script>
Problem
count value is not auto increment as Browser is Refrehed.
console.log(counters) //0 .
Any suggestion are most welcome.
After value solution code still not working
var counter = null;
if(sessionStorage.getItem("count") == null)
{
counter=sessionStorage.setItem("count", 0);
counters = 0;
}
else
{
counters= parseInt(sessionStorage.getItem("count"));
}
var page_count =counters;
if (page_count == 4)
{
dataLayer.push({'event':'mobilePromo-android'});
}
var page_count =counters;
console.log(page_count);
var height= $(window).height();
if (page_count == 4 )
{
$.ajax({
type: "GET",
url: "http://times.com/mobilepopuptracker?from=android",
});
$('body').html('<div class="row flush aligncenter popbx" style="height:'+height+'px">');
}
else
{
}
counters++;
console.log(counters);
function redirect()
{
var a=$(location).attr('href');
window.location.href=a;
}
issue output is till 1 it"S not incrmenting. what is wrong.
Output
if counter is set to 0 then it would auto increment to 1. and so on.
console.log(counters) //01 it should be auto increment.
Refrence link
https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Storage
you need to check first for session value is available
var counter = null;
if(sessionStorage.getItem("count") == null){
counter=sessionStorage.setItem("count", 1);
counters = 1;
}else{
counters= parseInt(sessionStorage.getItem("count"));
counters++;
counter=sessionStorage.setItem("count", counters);
}
Something like this should work
$(document).ready(function() {
var ls = sessionStorage.getItem("session-count");
if(ls) {
/*Do whatever here*/
var count = sessionStorage.getItem("session-count");
sessionStorage.setItem("session-count", parseInt(count) + 1);
} else {
sessionStorage.setItem("session-count", 1);
}
});
Trying to implement pagination for jQuery accordion using javascript. I found this link for a javascript class to implement accordion pagination. However, it's not behaving as expected. I played with it for a while but with no result. Can someone please help me figure where the fault is? I'd appreciated so much. Here I created JSfiddle for it.
Javascript code
var paginatorHandle = null;
jQuery(document).ready(function () {
jQuery("#dalist").accordion({
autoHeight: false
});
paginatorHandle = jQuery("#dalist").paginateAccordion({
"currentPage": 0,
"itemsPerPage": 3,
"paginatorControl": jQuery("#accordionPaginator")
});
// initial paginate call
paginatorHandle.paginate();
jQuery("#accordionPaginator .nextPage").click(function () {
paginatorHandle.nextPage();
});
jQuery("#accordionPaginator .previousPage").click(function () {
paginatorHandle.previousPage();
});
jQuery("#accordionPaginator .goToPage").change(function () {
var pageIndex = parseInt($(this).val(), radix);
paginatorHandle.goToPage(pageIndex);
});
});
//this is the main class
function AccordionPaginator(element, currentPage, itemsPerPage, paginatorControl) {
this.element = element;
this.currentPage = currentPage;
this.itemsPerPage = itemsPerPage;
this.paginatorControl = paginatorControl;
// does the actual pagination (shows/hides items)
this.paginate = function () {
var index = this.currentPage * this.itemsPerPage;
element.accordion("activate", index);
element.children().hide();
if (index < 0) {
this.element.children("div:first").show();
this.element.children("h3:first").show();
} else {
this.element.children("div:eq(" + index + ")")
.show();
this.element.children("h3:eq(" + index + "),h3:gt(" + index + ")")
.filter(":lt(" + this.itemsPerPage + ")")
.show();
}
this.refreshControl();
};
// increments the currentPage var (if possible) and calls paginate
this.nextPage = function () {
if (this.currentPage + 1 >= this.getMaxPageIndex()) {
return;
}
this.currentPage++;
this.paginate();
};
// decrements the currentPage var (if possible) and calls paginate
this.previousPage = function () {
if (this.currentPage - 1 < 0) {
return;
}
this.currentPage--;
this.paginate();
};
// sets currentPage var (if possible) and calls paginate
this.goToPage = function (pageIndex) {
if ((pageIndex < 0) || (pageIndex >= this.getMaxPageIndex())) {
return;
}
this.currentPage = pageIndex;
this.paginate();
};
// returns the maximum of pages possible with the current number of items
this.getMaxPageIndex = function () {
var items = this.element.children("h3");
var fullPages = items.length / this.itemsPerPage;
var restPage = items.length % (this.itemsPerPage > 0 ? 1 : 0);
return fullPages + restPage;
};
// fills up the paginator control
this.refreshControl = function () {
if (this.paginatorControl === null) {
return;
}
var pageList = this.paginatorControl.children(".goToPage");
pageList.empty();
for (var i = 0; i < this.getMaxPageIndex(); i++) {
pageList.append("<option value=\"" + i + "\">" + (i + 1) + "</option>");
}
pageList.val(this.currentPage);
};
}
jQuery.fn.extend({
paginateAccordion: function (options) {
var currentPage = options.currentPage ?parseInt(options.currentPage, radix) : 0;
var itemsPerPage = options.itemsPerPage ? parseInt(options.itemsPerPage, radix) : 5;
var paginatorControl = options.paginatorControl;
return new AccordionPaginator(this, currentPage, itemsPerPage, paginatorControl);
}
});
I made couple of changes to your code in JSFiddle and the pagination worked.
Here is the link to the modified jsfiddle.
http://jsfiddle.net/moLwmyyr/
I removed
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
And used JSFiddle Frameworks and Extensions to include jQuery
I changed the jQuery UI include to
<script src="https://code.jquery.com/ui/1.11.1/jquery-ui.js"></script>
I moved the
jQuery.fn.extend({
paginateAccordion: function (options) {
var currentPage = options.currentPage ?parseInt(options.currentPage, 10) : 0;
var itemsPerPage = options.itemsPerPage ? parseInt(options.itemsPerPage, 10) : 5;
var paginatorControl = options.paginatorControl;
return new AccordionPaginator(this, currentPage, itemsPerPage, paginatorControl);
}
});
Above your document ready method.
And changed the following line.
element.accordion("activate", index);
To
element.accordion("option", "activate", index);
The pagination works.
I observed some glitch when you go to the next page and click on the section 5, it is not collapsing section 4.