Load Content While Scrolling With jQuery
We generally have lots of content to present but can not load all of it at once as it may take too long.
I always loved the dZone’s Ajax content loading while scrolling feature and created a similar one using jQuery.
I’m pleased to share with WebResourcesDepot readers (Check the demo – scroll down to see new content in the demo)
This Ajax auto content loading can very be handy in almost every project. Don’t forget to bookmark it (del.icio.us link).
Download package includes a working demo coded with ASP with a test MySQL database. ASP code is just a simple query so you can switch it with a one you like easily.
What is loading content while scrolling?
When we are scrolling down a webpage, the code recognizes that you are at the bottom and auto-loads new content.
Why to use it?
It helps increasing the initial load speeds of pages faster and users will have to load only the content they see.
How it works? (Check the demo)
In our case, we have DIVS holding contents where every DIV ID is content’s database ID.
- Content structure is like:
<div class="wrdLatest" id=9>content</div>
<div class="wrdLatest" id=8>content</div>
- We create a function sending a query to a dynamic file with the DIV ID of the latest wrdLatest DIV (and also put a loader image):
function lastPostFunc()
{
$('div#lastPostsLoader').html('<img src="bigLoader.gif">');
$.post("scroll.asp?action=getLastPosts&lastID=" + $(".wrdLatest:last").attr("id"),
function(data){
if (data != "") {
$(".wrdLatest:last").after(data);
}
$('div#lastPostsLoader').empty();
});
};
- When a user scrolls down, we understand that the scroller is at the bottom with teh function below and fire the
lastPostFuncfunction.
$(window).scroll(function(){
if ($(window).scrollTop() == $(document).height() - $(window).height()){
lastPostFunc();
}
});
I have applied the demo to the DNSPinger service. Simply scroll down to see new content loading.
Dependencies
This is a very simple code that uses jQuery’s great dimensions plugin that helps us understand that we are at the bottom of the page. Update: Dimensions plugin is included with jQuery 1.2.6 and no need to include it as an extra.
Besides that, you can improve the code to detect the users sceen-size and load your initial content according to that screen size.
- Tags:
Javascript jQuery Scroll
- Filed under: Browsing, CC License, Extras, Goodies, License Free, MIT License, Tools, Tutorials
- 90 Comments
























90 Responses for "Load Content While Scrolling With jQuery"
I’ve been thinking about this few days ago.
My solution is like you but with one differenece:
For example we loading data by 10 elements.
At first load we get 20 and bind loadMore10 handler on element #10
elem1
..
elem10 loadMore
elem 11
…
elem20
When we scroll to #10 we load 10 more and set handler to #20.
So when we scroll to #20 we load ten more and set handler to total elements count – 10.
What we’ve got totally? User don’t see “loading” if hi don’t scroll 2 fast.
PS Sorry for bad english.
Oh, yea… In Safari 3.1 (Windows XP) it’s not work.
Thanks for putting this code out there it will come in handy in the future.
One thing to note, the div structure as it is now has 2 id attributes, the ‘wrdLatest’ should be a class, not an id.
I’m continually impressed on how simple it is to do things in jQuery. This is great that you are putting this out there for everyone to benefit from.
@Maxim,
That’s a nice way of doing that too I think. Yhanks for the input.
@Dan,
In the code wrdLatest is a class but I had mistyped it and fixed now.
jQuery & other major libraries are definitely great. What’s better about jQuery is, there are more plugins and information around IMHO.
Load Content While Scrolling With jQuery | nerdd.net…
\r\nAjax content loading while scrolling with jQuery tutorial.\r\nDownload package includes a workin…
If you follow my link there’s an example of just that without resorting to Custom JavaScript and also with WebControls in the content (meaning trapping events and so is implicitly supported in the content of your “live scroll area”…)
.t
Is this working with the latest jQuery 1.2.6, where the Dimensions Plugin is included into the jQuery Core?
[...] Muhaddisoglu has implemented the infinite scrolling pattern that Wikia Search has in place this [...]
@Karsten,
I didn’t know that Dimensions plugin was included to the core. That was a must.
I just tested now and from jQuery 1.2.6, there is no need to use Dimensions plugin in the script.
Just updated the post. Thanks.
Firebug tells me that “$(window).scrollTop is not a function”!
@Nicolas,
I just tried but couldn’t replicate it.
Did you get the error at the DNSPinger site or with the demo files, or both?
(DNSpinger is running a lower jQuery version, so I can compare)
I tried on a local web site on my computer, with jQuery 1.2.6, but just the part of your code that checks for the bottom of the page.
I’m using FF3RC2 on Mac OS X 10.4
That’s very interesting, i’m not sure how to use it in everyday situations though.
I believe it is kinda strange as this is a very common usage of Dimensions.
Sorry that I’m running a different OS and can not test it with OS X but I’ll install FF3RC2 and give it a try.
Does not work on Opera 9.5 b2 on Ubuntu 8.04.
This could be very useful for sites with lots of content below the fold. One thought though, id attributes should not start with a numeric character
Great effect
congratulations!
@Jamie,
To make it standards compliant I will update the ids with text and then split them to get the results.
Thanks.
[...] http://www.webresourcesdepot.com/load-content-while-scrolling-with-jquery/ [...]
[...] Si un ultim link interesant, efectul este similar cu cel din Google Reader: Load content while scrolling with JQuery [...]
[...] most commonly seen in Google Reader or the current DZone homepage. Web Resources Depot has a tutorial (and downloadable example) on how to achieve this using [...]
Well it’s limiting the user. One wants to scroll the way he is used to, so , I think thats not a real solution.
@foo,
I have to disagree with you.
The method does not change how a user used to scroll. It simply improves the standard scrolling pattern.
And it is successfully used in Dzone and Google Reader.
Only a quotations:
It only work when you scroll not using the scrollbar (using the mouse roulette, the keyboard or similar). If you use the scrollbar the event does not fire and does not add new content.
I supose that the scrollbar dont try go behind the actual content and the condition dont fire. I cant investigate it now but i want to comment it.
@FerniG,
There are some browser compatibility issues that I believe exists in jQuery Dimensions feature.
On the other hand, when I try scrolling with the scroller, mouse or keyboard in XP +FF2, IE, Safari & Opera, it all works fine.
Are you using OS X?
Sorry, i forgot especify my configuration. I tried it in FF 2.0.0.14 on windows XP SP3. In the same machine in IE7 it works perfectly. But in FF is shows this erratic behaviour.
In advance, i have tried it with and without extensions and in 2 differents machines.
It is not a important problem for me, only a interesting erratic behaviour, so dont worry and thanks for this usefull example
[...] http://www.webresourcesdepot.com/load-content-while-scrolling-with-jquery/ [...]
Ok how about if you are scrolling a div and not the whole page?
@Paul,
Then you will need to edit the code below:
($(window).scrollTop() == $(document).height() – $(window).height()){
to reflect your change.
Rather than the $(window) & $(document) you’ll need to use $(#divname) and some changes with the math too. But dimensions support divs or any element.
looking awesome!!! would it be possible to turn this into a pagination tool?
does this solution works with php too?
@bram,
can you explain more about turning it to a pagination tool?
@ganmo,
Yes sure, it will work with any language, just create PHP file with the query and update the JS to show that PHp file.
hi again, tried to follow your instuction to convert to php and i’m stuck in some point i can’t seem to fix (i’m still a novice in php). can you possible make a php-version of your content-load if you have time?
@ganmo,
Sorry that I may not find time to convert it to PHP.
On the other hand all the code has is 2 queries.
1st: calling the x amount of contents when the page is first loaded.
2nd: calling the new contents when the page is scrolled.
true, but maybe you could explain some codes for me instead? i’ll send you a mail with some questions i have about the code.
This is fantastic. A real nice use of JQuery.
wanted to report that this function only works for opera 9.0, and not the latest version 9.5. and i think it’s the dimension plugins that isn’t working correct.
[...] Load Content While Scrolling With jQuery [...]
i successfully implemented the infinite scroll on my php page. But it just found some weird behavior. Somehow when you scroll to the bottom of the page, it trigger the jquery functione more than one time, resulting the ajax load to be called several time and the content duplicated. You have any idea how to fix this?
@akmal,
Only thing I can think of is, the script is mis-calculating the end of the page and “close to the end” triggering once and “at the end” triggering again.
I advice that you scroll slowly and check it with firebug. And may be modify the JavaScript with adding extra pixels like:
if ($(window).scrollTop() == $(document).height() – $(window).height() – 10){
Maybe, this way it may calculate your webpage better.
Although I think this must not be the problem it is the only thing I can think of.
Thanks!
I manage to fix the problem, now the code do some checking to avoid calling the same page twice. You can see the working sample on the link above. Work like a charm. TQ for a very nice tutorial!
I have to agree with foo (June 10th, 2008 at 10:35 am).
Although I find it an interesting technique as an interface developer, I think it’s not something we have to implement just because we can. In my opinion implementing this leads to a situation where users might get totally lost in their (result) pages. Maybe there are sites where this technique can actually be of added value, but as a user I think I would find it quite irritating. Actually, I know: PicLens uses a similar technique (horizontally) and I often get lost in the enormous amount of results and I think this will happen here too.
On result pages I like to remember interesting results and scroll down further to look what else my search has brought me (there might be something even better than the remembered result). I do this by remembering where that particular result is globally positioned on the page. It’s something that happens kind of automatically in my head. With this infinite scrolling I wouldn’t easily find that result back, because its relative position on the page has changed. I don’t think I’m the only one who browses this way.
That’s why I think a paging system is the way to go from a usability point of view, just because that system gives the user a reference of where he’s located. A paging system using Ajax to decrease page loading would be the best solution I think.
[...] 参考资料:http://www.webresourcesdepot.com/load-content-while-scrolling-with-jquery/ [...]
[...] this is something you want to have a got att there’s a JQuery implementation for endless scrolling. As with many JavaScript tricks, you’ll need a server-side component to [...]
Not working in Chrome… too bad…
[...] Load Content While Scrolling With jQueryThis script allows to load the content “on the fly” – once th visitors has scrolled vertically to the end of the content block. “I always loved the dZone’s Ajax content loading while scrolling feature and created a similar one using jQuery.” [...]
[...] Auto Load Content While Scrolling (jQuery) | Demo [...]
I’ve written a jquery plugin and wordpress plugin along the same lines. However mine does not rely on a form post. check it: http://www.infinite-scroll.com
Your demo is down
@Janis,
Just fixed it..
[...] Load Content While Scrolling with jQuery This tutorial creates a scrolling effect similar to DZone’s. [...]
It is great.
I converted your ASP-code to PHP but it seems to be a bit buggy and i cant find the problem:
http://gelegrodan.netgeeks.se/wrd-scroll/scroll.php
Sometimes the scrolling stop work? Cant find the problem?
And it output the same data again sometimes?
The code:
http://gelegrodan.netgeeks.se/wrd-scroll/scroll.php scroll.php.txt
I forgot to say I am hoping someone can help me
@Linus,
The link seems to be working fine, doesn’t seem to stop & load twice. You fixed it?
No i haven’t do anything, for me it stopps on 2 now, missing one, and when i scroll down…nothing happens (otherwise your should see it request the page again in the statusbar)
@Linus,
I just tried again & can scroll to the bottom & the page queries few times.
You can try to put an alert to this part of jQuery:
$(window).height()){
lastPostFunc();
}
change to:
$(window).height()){
alert(”I am at the end”);
}
To see if the JS understandas whether you’re at the bottom.
On the other hand, if the demo works fine with you then it must be something with the PHP side I believe.
Like now when I scroll it requested like this:
scroll.php?action=getLastPosts&lastID=27
scroll.php?action=getLastPosts&lastID=22
scroll.php?action=getLastPosts&lastID=17
scroll.php?action=getLastPosts&lastID=12
scroll.php?action=getLastPosts&lastID=12
scroll.php?action=getLastPosts&lastID=7
scroll.php?action=getLastPosts&lastID=7
scroll.php?action=getLastPosts&lastID=2
scroll.php?action=getLastPosts&lastID=1
Double request at 12 and double at 7
Another problem seems to be if you have the searchbar open (ctrl+f in firefox)
But it don’t seems to be a problem with your example, so I cant find what I am doing wrong!?
$(window).scroll(function(){
if ($(window).scrollTop() == $(document).height() – $(window).height()){
lastPostFunc();
alert(”I am at the end”);
}
it works, until it comes to 2, then nothing!
And if I scroll up and down and then try again, the last one pops up…. sounds like your detection code is a bit inaccurate?
You should do an example code with the solution Maxim Syabro has, think it should work better, im too noob at ajax for doing it myself
All I can think of is server is, when scrolled down fast:
- a request is sent
- before it is loaded & jQuery not getting the latest loaded items id, a new request is sent with the old lastID.
To be sure,can u try to scroll slowly & if watching from Firebug, wait when a request is sent and after the new data is loaded scroll down again.
If this solves the problem then a control mechanism is needed there.
Well the problem seems to be the searchbar or the firebug window… it seems like it cant reach the bottom of the page if they are open.
You should make an example code with the solution Maxim Syabro has!
@Linus,
I may not have time to play with the code for now. Sorry for that.
BTW, at my side, the DNSPinger demo works with both Firebug & search panel open.
you use the same code as the demo for dnspinger? otherwise i would be happy if you could email me the code!
@Linus,
Yes it is the same code. I only call the data from another table.
Okej… I tested a bit and some strange thing happend… by misstake I typed a “,” behind:
“”
it seems to work every time!? sounds very odd.
So I changed the “,” to “hello” and it stopped worked… if i resize the window and maximize it again I can scroll down…. I think the “$(window).scrollTop()” is the problem…
I know it sounds like its my code thats acting strange, but my code seems to work for everyone except my self :S
Firefox 3.0.3
Adblock plus
Bugmenot
Firebug
Greasemonkey
Nightly tester tools
Tab mix plus
web developer
Well I found it it HAS to do with:
if ($(window).scrollTop() == $(document).height() – $(window).height()){
something is strange there, is there some other ways to check if im at the bottom of the page? or close to the bottom?
It works fine in IE for me, and on other computer it works in both IE and FF, so something wrong with my firefox
@Linus,
I’ve searched a way for checking if I’m at the end of the page so much & couldn’t find then created this method.
I’m sure there is an easier way but I don’t know about it.
That function detects if you hit the “end” of the bottom.
You can configure a bit flexibility to it like “when you’re close to the bottom” which may be a solution for browser based calculation differences.
Just add a few pixels to the function. Sorry that I didn’t look to this code for a long time & after a busy day I just couldn’t concentrate well
..
[...] Load Content While Scrolling With jQuery [...]
Not sure if the author is still monitoring this, but I’ve been trying to implement this in a PHP application however it’s not hiding the previously loaded items (ie, loading both up and down).. any ideas why this would happen?
@Jeff,
I couldn’t very well understand the problem. “Hiding the previously loaded items”? Not sure if it should do this.
Do u have an URL where the problem occurs?
I dont have a URL that I can show, it’s privately being developed but I essentially want to have it “un-load” or “hide” the ones above as it loads down, so it does the jQuery load both down and up?
Because I have a table of 1000+ rows and it tends to lag the browser so I think if I could get it to load both up and down it’d be better?
Well, this example doesn’t hide the ones at the top. You should add this part to the code.
I have a page which has lots of rows, each row is assigned an ID.. is it possible for your code to load the page from a specific row without loading the ones before?
@Sami,
I’m sure the code can be edited to your needs.
If I understood well, you can run the SQL query which loads the rows in that way (like “WHERE ID > 25″).
Does any one have the code already converted to php?
Can not convert it by my self…
Looks easy enough.. but I’m not very familiar with neither php nor asp.. but it would be much better to have it in php.
can some one help me please?
cheers
I guess since the demo wont work with Opera the script generally doesnt work with Opera ?
@thc,
I know that it works in Opera 9.0 but there is a probşem with Opera 9.5+.
Although I have not looked at it further, I guess it can be fixed by using the latest version of jQueryç
Hai please send me jquery tutorials
For people after are php version of the script ive made one just having a few server problems so there’s no demo yet
but here’s the zip
http://dev.seanhood.co.uk/scrollLoad/scrollLoad.1.0.zip
Once ive sorted the problems i’ll pop back with a link
Follow me: http://twitter.com/SeanHood
hi ive now got my server problems fixed so here’s a demo
http://dev.seanhood.co.uk/scrollLoad/
just making a proper info page for it now
Sean
very nice and helpful.
thnx to author.
http://www.zamshed.info/tech/
Very nice application. i can get starting re-designing my website.
Worst interface “enhancement” ajax has brought to the web world yet. I get so lost when I am scrolling, and then all of a sudden the page size doubles. It’s just confusing. I’ve seen this first on slashdot, and then dabbled with a firefox plugin that enables this behavior on normal pagination pages; and have grown to hate using this interface. I would much rather have pages (which then either replace the content, or append to the bottom of the page). At least this is a known action (I click on a button/link and something will happen), rather than an unknown (Hmm, if I scroll maybe the page will change size).
This is “ALMOST” what i have been looking for for ages …..
Good work Sir !
Question:
Is it possible to add an “on page load” function that would automatically start the scroll? and if so – HOW ?
ie. an automatic scroller that starts on page load, like the rolling credits at the end of a movie.
I have been struggling with this and your help would be Awesome.
Cheers
@patrick,
I both agree & disagree. For me, it depends the place it is used at (like Google Reader works amazing for me).
@Coddie,
I haven’t done anything yet but “animate” function can help you. I suggest you check the jQuery documentation for that.
is there any way to load more content on click instead by scrolling?
got it….
create a div: Load more
then add this inside of the document.ready function:
var loadMore = $(’#more’);
loadMore.click(function(){
lastPostFunc();
});
I removed the scrolling function because my mouse scroll wheel would execute the same query 4 times in a row.
Nice one mate. I have also added the link to your post in my Ultimate collection of top jQuery tutorials, tips-tricks and techniques to improve performance. Have a check below:
http://technosiastic.wordpress.com/2009/09/24/collection-of-top-jquery-tutorials-tips-tricks-techniques-to-improve-performance/
Hi, I am looking at your demo with MSIE 8.0 and onces it starts to scrool with the mousewheel, it creates dupes of every 5 records?