Scroll to the bottom of the page, reload it then repeat - javascript

I have checked all the possible questions that could be related to this but I cant seem to find anything that suits my case, either the answers were not good or incomplete.
In my case I have a html page with some php, displaying competition results. As the competition is live the page with results should scroll to the bottom of the page and then the page should refresh (so the possible new scores come in) and then repeat again and again. What would be the best solution for my problem?
The page size/length would increase as more data will come in the tables which are on results page.
Image:
EDIT:
This code now scrolls to the bottom of the page and then jump back to top and repeat and its exactly what I want, but I would like a page to refresh every time I hit the bottom and after this go to the top.
$(function() {
var pageScan = {
speed : 10000,
loop : true,
delayRestart : 1000,
start : function(){
pageHeight = $('body').height() - window.innerHeight;
pageScan.proc(pageHeight);
},
proc : function(to){
$("body").animate(
{scrollTop: to},
pageScan.speed,
"linear",
function(){
if (pageScan.loop) {
setTimeout(function() {
window.scrollTo(0, 0);
pageScan.start();
}, pageScan.delayRestart);
}
});
}
};
pageScan.start();
});

You can add some JavaScript to your page:
<script>
window.scrollTo(0,document.body.scrollHeight);
setTimeout(function (){location.reload()},5000);
</script>

This might be what you are looking for:
// Test data, ignore
for(i = 1; i < 21; i++) {
$('#results').append('<p>Test Result No.' + i + '</p>');
}
// Check every second (for example) if there is new data
// In this example there is always data
window.setInterval(function(){
update_results();
}, 1000);
// Check for new results
function update_results() {
$.ajax({
type: 'POST',
// Test data, ignore
data: {
html: 'new result'
},
// your ajax.php file
url: '/echo/html/',
success: function(data) {
// Append new results to $('#results');
// You might want to give back an array and loop through it with $.each(data, function() {});
// you might also want to check for "false" if there are no new results
$('#results').append('<p>' + data + '</p>');
// Scroll to bottom smoothly
$('html, body').animate({ scrollTop: $(document).height() }, 'slow');
}
});
}
jsfiddle
In your ajax.php-File you can echo the new scores:
echo json_encode($scores);
Given that $scores is an array of your scores which you probably have from your database.

Related

AJAX load when reach bottom of container

I can't figure this problem out.
I use this JS call to load ajax content when I arrive at the bottom of the page:
$(window).scroll(function() {
if($(window).scrollTop() + window.innerHeight == $(document).height() ) {
and it works well, but now I want to change for loading the content when I reach the bottom of my container... I am trying this:
$(window).bind('scroll', function() {
if($(window).scrollTop() >= $('#postswrapper').offset().top + $('#postswrapper').outerHeight() - window.innerHeight) {
It loads the content when I reach the bottom of the container, but it loads it like 5 times... It's like as if it does a loop 5 times each time.
I want it to load ONCE, then when I go back DOWN the page and I reach the "NEW BOTTOM" of the container, load data 1 more time...etc
I tried many variables, but I can't figure it out. Any suggestions?
FULL AJAX CODE
$(window).bind('scroll', function() {
if($(window).scrollTop() >= $('#postswrapper').offset().top + $('#postswrapper').outerHeight() - window.innerHeight) {
$('div#loadmoreajaxloader').show();
$.ajax
({
url: "loadmore.php",
method: "get",
data: { page: pageNumber, perpage: perPage, search: "<?=$search?>", blogtag: "<?=$blogtag?>"},
success: function(html)
{
if(html)
{
$("#postswrapper").append(html);
$('div#loadmoreajaxloader').hide();
pageNumber++;
}
else
{
$('div#loadmoreajaxloader').html('<center>No more posts to show.</center>');
}
}
}); // close AJAX
} // close if()
}); // close $(window)
Scroll top is executed few times after you have the set true for the condition:
if($(window).scrollTop() >= $('#postswrapper').offset().top + $('#postswrapper').outerHeight() - window.innerHeight)
Here is a test fiddle for the window scroll, it always fires when you move the scroll and your condition does not limit the inner scope to execute only once.
test scrool event
Edit: simplest way is to use a lock while the ajax request is executing and while you are updating the UI with new content.
Why build something like this yourself when there are plenty of libraries out there? Just use an infinite scroll library that meets your needs. As you already use jQuery:
http://www.sitepoint.com/jquery-infinite-scrolling-demos/
But that's not the answer to your question. You should add a boolean to check if you're already loading new content. Let's say: loading. Initially set this boolean to false. If you request new data, set the boolean to true and in the check scroll statement add a check for this boolean. After adding the newly loaded content set the boolean to false again.
Fully working code:
var loading = false;
$(window).bind('scroll', function() {
if(!loading && $(window).scrollTop() >= ($('#postswrapper').offset().top + $('#postswrapper').outerHeight() - window.innerHeight)) {
loading = true;
$('div#loadmoreajaxloader').show();
$.ajax({
url: "loadmore.php",
method: "get",
data: {
page: pageNumber,
perpage: perPage,
search: "<?=$search?>",
blogtag: "<?=$blogtag?>"
},
success: function(html) {
if(html) {
$("#postswrapper").append(html);
$('div#loadmoreajaxloader').hide();
pageNumber++;
loading = false;
} else {
$('div#loadmoreajaxloader').html('<center>No more posts to show.</center>');
}
}
}); // close AJAX
} // close if()
}); // close $(window)

Scroll down to bottom. Then reload page and do it again

I'm using this simple code, and it's working fine.
$("#mydiv").animate({ scrollTop: $('#mydiv')[0].scrollHeight}, 20000)
What I would like is to after the bottom has been reached immediately go back to the top of the page and start scrolling down slowly again. How would one achive something like this in JQuery?
Thank you guys!
you can jump back to the top of your page using the following javascript function:
function jump(elementId){
var location = document.getElementById(elementId).offsetTop;
window.scrollTo(0, location);
}
just use the id of some element at the top of your page.
Not sure what you are trying to do and what "reload" means but here is a quick snippet to get you started:
JSnippet Demo
As you can see its configurable and easy to understand:
$(function() {
var pageScan = {
speed : 10000,
loop : true,
delayRestart : 1000,
start : function(){
pageHeight = $('body').height() - window.innerHeight;
pageScan.proc(pageHeight);
},
proc : function(to){
$("body").animate(
{scrollTop: to},
pageScan.speed,
"linear",
function(){
if (pageScan.loop) {
setTimeout(function() {
window.scrollTo(0, 0);
pageScan.start();
}, pageScan.delayRestart);
}
});
}
};
pageScan.start();
});
We could do something easier like this:
(function (){
var div = $('#myDiv'),
infiniteScroll = function () {
//---gets the bottom of the page value
var bottomHeight = div[0].scrollHeight;
var callback1 = function () {
//once it gets into this callback function
//it resets the position to zero
div.scrollTop(0);
//invokes again the function infinite scroll
infiniteScroll();
};
div.animate({scrollTop:bottomHeight},20000,callback1)
};
//starts the function for the very first time
infiniteScroll();
})();
I created a codepen so you can see it working and play with it:
http://codepen.io/dieggger/pen/VLoZWv?editors=101

jQuery animate dynamic elements one at a time

Let me preface this by saying I have addressed this thread trying to resolve my issue, but to no avail:
Fade in each element - one after another
I thought it would work quite handily if the elements weren't dynamic content, but I made a test div and filled it with thumbnails, and a button to click and assigned similar code, but it still just flat out removed all of the elements without animation or hesitation.
Right now, what I have looks like this:
function OnThumbSuccess(response) {
var $thumbs = $('#Gallery .thumbWindow .thumbReel');
var files = $.parseJSON(response.d);
$thumbs.children().each(function (i) {
$(this).delay(i*300).animate({ 'opacity': '0' }, 500, 'easeOutSine');
$(this).remove();
})
//make sure the thumb reel resets to its original position
$thumbs.css('left', '0px');
//loop through the array of json objects
for (var i = 0; i < files.length; i++) {
//images[i] = files[i].fileHREF;
InsertHTML(files[i].thumbHref, i);
}
}
So, it's supposed to fade that element out, then remove it. It has no problem removing it; it's the animating it that it seems to fail on.
After some tinkering around, I have discovered that I CAN indeed animate them however I please, provided I get rid of $(this).remove(). That would be fine, if I didn't need to get rid of those elements.
It doesn't seem to matter what I do. I've tried chaining the .remove() to the end of the animate function, I've tried setting a delay equal to the number of elements before emptying the div. I've tried moving the code to populate the thumbnails div from the OnThumbSuccess function to the ajax.done() function.
I'm really at a loss as to how I can do this elegantly. Please let me know what, if any other details I can provide.
I made this test fiddle, maybe this will be of some help: http://jsfiddle.net/kum8d7k9/
Well, in the process of writing this question, I have come up with the following solution, which seems to work quite well:
function GetThumbnails(category) {
$.ajax({
type: "POST",
url: "Filenames.asmx/GetFiles",
contentType: "application/json; charset=utf-8",
data: '{ "folderName" : "' + category + '"}',
dataType: "json",
success: OnThumbSuccess,
failure: function (response) {
alert('failure');
}
}).done(function (response) {
//alert(response.d);
var files = $.parseJSON(response.d);
var $thumbs = $('#Gallery .thumbWindow .thumbReel');
if ($thumbs.children().length > 0) {
setTimeout(function () {
$thumbs.empty();
//loop through the array of json objects
for (var i = 0; i < files.length; i++) {
//images[i] = files[i].fileHREF;
InsertHTML(files[i].thumbHref, i);
}
}, $thumbs.children().length * 300);
}
else {
//loop through the array of json objects
for (var i = 0; i < files.length; i++) {
//images[i] = files[i].fileHREF;
InsertHTML(files[i].thumbHref, i);
}
}
}).fail(function (response) {
alert(response.responseText);
});
}
function OnThumbSuccess(response) {
var $thumbs = $('#Gallery .thumbWindow .thumbReel');
$thumbs.children().each(function (i) {
$(this).delay(i*200).animate({ 'opacity': '0'}, 200, 'easeOutSine');
})
//make sure the thumb reel resets to its original position
$thumbs.css('left', '0px');
}
I have moved the .empty() function to the $.ajax.done() function and set a timeout on it equal to the number of child elements I have to fade multiplied by the animation duration with a little wiggle room.
Next I'll have to conjure up a way to transition those elements in as well. This has been most educational, but if someone has a better solution in mind, I'm all ears.
You don't want to call .remove() until after the animation completes so you will need to use the complete callback function of jQuery animate, http://api.jquery.com/animate/.
$(this).delay(i*300).animate({ 'opacity': '0' }, 500, 'easeOutSine',
function() {
$(this).remove();
}
);
The chaining did not work as the animate function returns immediately rather than after the animation is complete.
$('#remove_me').animate({
opacity: 0
}, 500, function() {
$(this).remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="remove_me">testing remove</div>

How can I keep scoll position on dynamic refresh div?

I'm searching a few hours ago for this, I can't finr anywhere.
I use simple Jquery script to refresh a div. I want to see my PHP output in that div.
$script = "
<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js\"></script>
<script type=\"text/javascript\">// <![CDATA[
$(document).ready(function() {
$.ajaxSetup({ cache: false }); // This part addresses an IE bug. without it, IE will only load the first number and will never refresh
setInterval(function() {
$('#uziRefresh').load('http://mypage/refresh.php?a_a=".$kinek[1]."');
}, 6000); // the \"3000\" here refers to the time to refresh the div. it is in milliseconds.
});
// ]]></script>
";
My problem is. When it refreshing it go to top position of div scroll. I would like to keep the current position, becouse my users my would like to read all content of the div. I would like to make a simple chat application. But it's bad cos always go to top.
How can I solve this? Anyone has a solution?
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$.ajaxSetup({
cache: false
});
setInterval(function() {
var div = document.getElementById("uzidoboz").scrollTop;
$('#uziRefresh').load('/modulok/belso_levelezes/refresh.php?a_a=<?php print($kinek[1])?>', function(){
$("div.uzidoboz").scrollTop(div);
})
}, 6000);
});
</script>
This is my full solution. I'm sorry, I missed some div names, but with correct names the last solution not yet worked. This work fine. First I get the current scrolltop, reload the div, and set the scrolltop.
It runs in every 6000 millisecond. It's simple now and work. I have my divs. uzidoboz div have got overflow. My content is in that. But I load it all to the uziRefresh div...
Check this solution. I have removed your comments sorry!.
$(document).ready(function() {
$.ajaxSetup({
cache: false
});
var updateScrollPosition = function() {
var div = $('#uziRefresh');
div.scrollTop(div.height());
};
setInterval(function() {
$('#uziRefresh').load('http://mypage/refresh.php?a_a=".$kinek[1]."', updateScrollPosition);
}, 6000);
});
To be precise use this -
$script = "
<script type=\"text/javascript\">// <![CDATA[
$(document).ready(function() {
$.ajaxSetup({
cache: false
});
var updateScrollPosition = function() {
var div = $('#uziRefresh');
div.scrollTop(div.height());
};
setInterval(function() {
$('#uziRefresh').load('http://mypage/refresh.php?a_a=".$kinek[1]."',
updateScrollPosition);
}, 6000); // ]]>
";

.offset().top returning the wrong value

I'm having a bizarre issue that I don't know how to solve and was wondering if you guys could help.
A bit of background: I have been asked to create a system where subpages of a page in wordpress are loaded on the end of that page in an infinite scroll. This is working correctly.
They also want the top nav links to load all content upto and including the page they clicked and then scroll to it.
If I scroll down (loading the pages) and then click a top nav link the scroll works correctly. However if I load NO further pages before clicking one of the links, the pages will load, and the scroll will start, but will only get some of the way before stopping. This is due to an incorrect value being given by offset().top. My question is why ?
function ajaxloadnscroll(index) {
//If the page has already been loaded then just scroll to it
if (pages[index].loaded) {
$('html, body').animate({
scrollTop: $("#" + pages[index].name).offset().top
}, 2000);
return;
}
//Loop through pages up to one clicked.
for (i = 0; i <= index; i++) {
current = i;
if (!pages[current].loaded) {
$.ajax({
url: pages[i].url,
async: false,
context: document.body,
success: function(data) {
if (data) {
$("#tempload").before(data);
pages[current].loaded = true;
if (current == index) {
$('html, body').animate({
scrollTop: $("#" + pages[current].name).offset().top
}, 2000);
}
}
}
});
}
}
//Increment current in order to load next page object on scroll.
current++;
return false;
}​
Any help you could give me on this issue would be really appreciated!

Categories