Load Content While Scrolling With jQuery

62°

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).

jQuery Load Content While Scrolling

Download Load Content While Scrolling With jQuery

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 lastPostFunc function.

$(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.

  • Maxim Syabro

    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.

  • Maxim Syabro

    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.

  • 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?

  • @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.

  • Larry

    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.

  • foo

    Well it’s limiting the user. One wants to scroll the way he is used to, so , I think thats not a real solution.

  • Umut M.

    @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.

  • FerniG

    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.

  • Umut M.

    @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?

  • FerniG

    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

  • Paul

    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.

  • bram Vogelaar

    looking awesome!!! would it be possible to turn this into a pagination tool?

  • ganmo

    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.

  • ganmo

    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.

  • ganmo

    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.

  • ganmo

    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.

  • 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!

  • Jack Michaelson

    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.

  • merzu

    Not working in Chrome… too bad…

  • 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..

  • Mensur Tanovic

    It is great.

  • Linus

    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

  • Linus

    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?

  • Linus

    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.

  • Linus

    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!?

  • Linus

    $(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.

  • Linus

    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.

  • Linus

    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.

  • Linus

    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

  • πŸ™‚ Gr8 to hear that it is solved..

  • Linus

    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 :)..

  • Jeff

    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?

  • Jeff

    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.

  • Sami

    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”).

  • Pedro

    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

  • thc

    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ç

  • Nibohs

    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.

  • patrick

    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).

  • Coddie

    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.

  • aaron

    is there any way to load more content on click instead by scrolling?

  • aaron

    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/

  • Joakim

    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?

  • Yeah, this demo has a bit of a bug where if the scroll event fires multiple time before the AJAX is finished doing it’s thing (think scrolling up and down at the end of the page) it will fire several times.

  • Nitesh Sharma

    Hi i want to apply the same thing on iframe such that scrolling the iframe loads the rest og the content.Is that possible using this jquery script?

  • Robert Brown

    Can anyone tell me if it is possible to do this scrolling from left to right rather then down the page?

    We have a large map that I would like load in sections but only download the section which the visitor wishes to see.

  • I’ve made some changes to the code that only make one request at a time and to call the update before the scroll gets right to the bottom. The changes are here if you want to see: http://learninglamp.wordpress.com/2010/01/30/endless-scrolling-with-jquery/ . I’ve only tested this in FF on a Mac, the demo pulls live images from Flickr so I can’t guarantee they’re all “safe”.

    @Robert have you tried a lazy loader solution: http://www.appelsiini.net/projects/lazyload

  • @Andrew,

    You can also add a small equation to the code above to fire the load event anytime you want:

    Just change:
    if ($(window).scrollTop() == $(document).height() – $(window).height()){

    to

    if ($(window).scrollTop() -20 == $(document).height() – $(window).height()){

    would fire the event when you’re 20px close to the bottom.

  • @umut I found using == would only fire if you were at exactly that scroll position and when I was testing it the event didn’t seem to get fired reliably (if you scrolled too fast or jumped to the bottom somehow), using > means it will fire anytime you’re in the bottom section. I also prefer setting it as a percentage as it doesn’t matter how large the window is, your buffer area should be proportional.

  • Not having the content listed in the HTML for search engines is horrible for SEO.

    This approach is fine for images (which produce little SEO benefit), but I would never use it for loading additional content.

    If you somehow sniffed the USER_AGENT for google/bing/etc. bots, and displayed all of the content for search engines to index, then it might be a plausible solution.

  • vishwa rao

    Is this available in .NET C#?

  • Ralph

    Very nice tutorial, very helpful.

    Just would like some advice on what to change to make it automatically load the next section, ie not wait for the user to scroll to it, but just load chunk by chunk. I have a case with thousands of rows of data and I think it would make faster active page if I could load 50 lines, and the next 50 when they are loaded and so on until the end.

    Would I need to change much from your script? I’m thinking only the function that recognizes when the scrolling to the bottom happens.

    Thanks for your input in advance.

  • @Ralph,

    I think that is a great idea if “all the content has to be loaded” as loading too much content will simply make the page heavier, freeze the browser, etc.

    I think you don’t have to go with this script as there is not many similar stuff.

    You’ll need a recursive function (that loads content via Ajax) which re-runs when it is complete.

  • Peter

    Is it possible to have the jquery load hidden content in div’s on a flat page rather than pulling it from a database?

  • @ Eric: If you have to scroll this amount of content (e. g. 20+ divs with lots-o-damn lines), not even Google, Bing, […] bots will take it from div 14 … the bot only visits a couple of seconds and grabs. And if your site – e. g. – starts with tons of javascript*, guess what Google & Co. takes or how useless they’ll “rank” your site … so: if your first divs got your SEO relevant content, everything will be fine …

    *remember CDATA to mask!! πŸ˜‰

  • Kelly johnson

    You do know that all javascript should be put at the bottom of your page, just above the closing tag, right?

    That will open some space for the bots

  • Emmanuel

    There is a problem with this code if you change the zoom level of the browser to less than 100% (Didn’t try with more than 100%). If you change it, the action doesn’t get sent because the dimensions have changed. Any idea how to fix this???

  • Mio

    Hi ! First of all, nice tutorial !

    Do you have any idea on how to stop the requests from happening once the maximum is reached ?

    Take this for example: you scroll down to the last element, then you scroll up a bit, and then down again. I’m trying to use the ‘if (data != “”)’ statement and a trigger variable, but I can’t seem to make it stop sending requests.

  • @Mio,
    A good way to do this can be:
    – adding an empty and hidden element (lets say “div”) and lets say its id is “controlEndOfData”.
    – in the PHP part, send the response with a special delimiter that decides whether it is the end of the data or not like: “the-response-generated-by-php|0 (or 1 at the end)”
    – split the response at the javascript part and get the 0 or 1
    – if it is 1 (the end of data), insert 1 to the $(“#controlEndOfData”).html().
    – to the code where a new query is sent, add a “if then else” clause which checks if the $(“#controlEndOfData”).html() is empty or not, if empty send the request, else do not send.

    Can sound complicated but it is simply a mix of PHP & JS.

  • Thanks, exactly what I was looking for.

  • moment

    thank you for this code. I have a problem with chrome. It calls the post function twice somehow. It only happens in chrome though. I tried to add some offset to the trigger height but it stopped working completely. Any ideas?

  • Zelf

    How would I trigger lastPostFunc() in a div with a scrollbar? So triggering is based off of the height of the div with scrollbar and whether the user is at bottom of that div?

  • Mark Evans

    Hey this doesn’t work on Chrome on a mac.

  • Tim

    It is invalid html to have an id start with a number. You should fix that.

  • emcee

    This will solve the double call on the lastID, that problem happens when you scroll very fast, to prevent that, we will call the function before it reaches the very bottom of the page and put a delay so while browser is processing the first call, it will not interfere even you scoll fast, works on all browser, should for for you as well πŸ™‚

    $(document).ready(function(){
    var fetching = false;

    function lastPostFunc()
    {
    fetching = true;
    $(‘div#lastPostsLoader’).html(”);
    $.post(“../user/load2.php?lastID=”+$(“.comment:last”).attr(“id”),

    function(data){
    if (data != “”) {
    $(“.comment:last”).after(data);
    setTimeout(function(){
    fetching = false;
    },300);
    $(‘div#lastPostsLoader’).empty();
    }
    });
    };

    $(window).scroll(function(){
    var bufferzone = $(window).scrollTop() * 0.20;
    if (!fetching && ($(window).scrollTop() + bufferzone > ($(document).height()- $(window).height() ) )){
    lastPostFunc();
    }
    });
    });

  • Thanks a lot … i am searching this last few months… its really helpful for me to develop buffering style content load

    thanks again.

  • by the way >>
    your code is cool but not valid: id and name attributes must begin with a letter, not a digit

  • vishwas

    Hi i am using this if ($(window).scrollTop() -20 == $(document).height() – $(window).height()) it’s not working

  • Disco181

    Hi,

    I’m using your code as the basis of a project I’m working on. I have a little problem which I’ve posted on the jQuery forum but I’ve had no response.

    Would you care to take a look?

    http://forum.jquery.com/topic/issue-with-scroll-loader-fade-in-in-ie8-using-jquery-1-5-1

    Thanks

  • @Disco181,

    After a quick look, it can be the id’s being mis-formatted ids:
    id=” 15 “>

    Suggest changing the code to produce:
    id=”15″>

    Also, rechecked the demo at WRD and it works ok at IE. Sorry that not sure what the issue is but you can check the Ajax requests with Firebug Lite at IE and try locating the issue afterwards.

  • Disco181

    Hi Umut,

    Thanks for the feedback. After a lot of testing it would appear that the issue has something to do with the way IE handles scrolling when being initiated by a scroll wheel. Clicking on the scroll bar and moving down the page works fine. Using the scroll wheel causes the issue. No solution yet, but will post if I have any joy.

    Thanks again.

  • david

    will the technique works on major browsers like IE8/9, FF3/4, Chrome and Safari?

    will the technique works on SEO and GA?

  • Rajee

    Hi,
    Its very helpful for me. Thanks.
    But it loads twice the second time.
    I tried to test using alert box and found that lastPostFunc(); fires twice.
    Y is it so?
    Its loading fine when i scroll first time.
    But on second time its firing twice.
    Why is it so? Kindly help me to resolve. Its very urgent.

  • MR

    Hi ,

    also the loading panel loads every time i scroll and multiple loading panel shows. How to clear the loading panel once it loads after every scroll.
    The div.empty() does not clear the image.

    Thanks,
    MR

  • @Rajee,
    I can’t reproduce the issue here.

    Which OS + browser are you using?

  • Rajee

    Hi ,

    I am using xp and google chrome.
    Now i have an imp issue to be solved with this.
    I have a master page and i am loading the content from user control. In my user control i have many divs with different controls.
    In one of my div i am using List view to display datas.
    I want to load the list view while scrolling the page.
    How to do it?
    I am using scroll for particular div instead whole page.
    Now if i scroll its loading the whole page contents again with datas.
    Instead i want only the list view to be loaded again.
    Kindly help me as this is important for me.

    Thanks,
    Rajee

  • MR

    Hi ,

    If i have any other controls in my page other than the div to be loaded while scrolling the whole page is loading while scrolling with that div. Why is it so? Where i am going wrong.
    Kindly help me on this. Its urgent.

  • MR

    Hi,
    Also can you provide me with your mail id so that i can send you my sample code and screen shots of the issues i am getting.
    As i was impressed with your code sample i have scheduled my developing time as 2 days. It worked fine in my sample application where i have only list view without any other controls. But if i am using any other controls or master page actually whole page is getting reloaded and comes twice as i scroll. Its a big problem for me now.
    Kindly help me in this.
    Its critical situation for me.

    Thanks

  • ojiepermana

    cara seperti ini bisa berakibat double post, jika halaman belum selesai di load dan kita melakukan scroll lagi, saya saran mengggunakan
    async: false,

    seperti ini :
    $.ajax({
    async: false,
    url:your_page_link,
    success: function (data) { $(‘table.special tbody’).append(data); },
    dataType: ‘text/html’
    });

    di dalam fungsi lastPostFunc

    saya harap ini dapat membantu

  • check what I did with your script! I had to modify some bit to add a “no more posts” once you reach the end of the page! Here is the script.

    $(document).ready(function(){
    var fetching = false;

    function lastPostFunc() {
    fetching = true;
    $(‘div#loadmoreajaxloader’).html(”);
    $.post(“loadmore.php?id=&uid=&ref=profile&t=&lastid=””loadmore.php?id=&uid=&ref=profile&lastid=””loadmore.php?uid=&t=&lastid=””loadmore.php?uid=&lastid=”+$(“.postitem:last”).attr(“id”),

    function(data){
    if (data != “”) {
    $(“.postitem:last”).after(data);
    setTimeout(function(){
    fetching = false;
    },300);
    $(‘div#loadmoreajaxloader’).empty();
    } else{
    $(‘div#loadmoreajaxloader’).html(‘No more posts to show.’);
    }
    });
    };

    $(window).scroll(function(){
    var bufferzone = $(window).scrollTop() * 0.20;
    if (!fetching && ($(window).scrollTop() + bufferzone > ($(document).height()- $(window).height() ) )){
    lastPostFunc();
    }
    });
    });

  • Simon

    Hi
    I am having the same issue as you have tried to help with. I tried to use your code justin, but you have two seperate functions and you cannot use the variable ‘fetching’ in the $(window).scroll part because it is not defined or passed over.

    Is there a better way to do this that doesnt simply set a timeout?

    I want to accurately display more products and not when they hit the bottom of the page as it looks jumpy, but when they get about 20% from the end. I have set the scroll part to ‘>=’ rather than ‘==’ which is working but obviously calling the php script lots of times

  • Thanks for the great tip. I was always wondering how I can trigger such event. I made a bit of change to your code and get my function called, when reaching 90% of the document height.

  • Ajay Sharma

    I have magnged it on my product listing page. When i scroll down my page with browser it loads next set of data (product) with in the same page for ex. it loads every time 20 new products when scroll down page. When i clicked on 100th product , its redirect me to 100th product detail page , when i clicked back button of browser , browser can not show me the same location and position on product listing page.

    what should i do for it ?

  • @Ajay,

    That seems like a challenging issue but not hard. There seems to be 3 ways at first thought:
    – remember the latest position with sessions
    – remember the latest position with cookies
    – on each load of 20 products, change the URL with an hashtag(#)

    when the user returns back to that page, on initial load, display the first x items that session/cookie/hashtag tells.

  • Sweet πŸ™‚
    Whatever makes the website load faster is interresting for me. Have to look into this:-)

  • i cant make it in php file .. pls i need some help

  • Mau

    Hi, thanks for the tip man!!
    I don’t know jquery and I’m having some problems.
    Can I combine it with “includes” of php script?
    Like and so…
    Thanks for your time dude.

  • Daniel Pinho

    Hi.. I am trying to use your code to show a grid (using table).

    The problem occurr when I scroll to the bottom, because my new table is inserted betwen the first one.

    You can see the problem on http://www.papelgratis.com.br/wrd-scroll/scroll3.asp

    Can you help me ?

  • @Daniel,

    Not totally sure as I can’t see the edited .asp file but you may be inserting tables inside rows/columns.

    I suggest inserting new rows and make sure they are inserted just after the last row.

  • The Script working is fine But there is scroller problem can u kindly check it once

  • sanam

    Hi, sorry to ask such a stupid question, but I’m pretty new to this whole thing, and what I’m confused about is how exactly am I meant to get this feature onto my site? Am I meant to copy and paste the code into my site or download something…? I could really do with some help, thanks

  • @sanam,

    The code is not a plug ‘n’ play solution.

    It explains how the concept works and brings a working code for it but the developer should adapt the code to his/her website.

  • gino

    How to maintain the state.
    I have a scenario that contains a select button and once the user clicks the select button the few more controls will be loaded based on the selected item. In such cases I am loosing the state. How can I achive this.

  • Thanks for this really helpful solution.
    But what if data is coming dynamically from DataBase and the amount of data is unknown?

  • @Ashish,

    That shouldn’t be a problem as you limit the number of records being pulled each time.

  • Stefan Bakker

    @Umut M,

    Love the code! Nice work! I Have 2 more questions:

    1. When I’m at the end of my page, he keeps showing the loadmore div. How can I change this that he won’t show anymore after postitem id = 1?
    2. I would like to “delay” the loading of the next items. For example, when I scroll down, I want to show the div “loadmore” for 3 seconds and then he has to show the results. Is this possible and how do I do this?

  • Nayan

    How can i use it for horizontal scrolling as i want to append data when use scroll horizontally? Please suggest.

    Thank you

  • Cmasmas

    en php oop pliS!!??

  • Thanks a lot for the tutorial … I’m trying to adapt the script to included into my theme filter js script …

    Nice one !

  • Hi,

    Thanks for the script. This is exactly what I wanted.

    I am not sure why, but my request is getting executed two times simultaneously. Can you please help me how to check what the problem is?

    Himanshu

  • I look for the code like this, will try if working,Thanks,

  • SSM

    I’ve tried in IE 9, it doesn’t load the content while scrolling.

    Same code works fine in Firefox 14 and Chrome 20.

    Is this related to plug in support IE 9?

    Thanks

  • chandu

    I have downloaded the source file but how to use it in VS2008?How to make it working?

  • Shen

    Thank you for your code, it is simple but very useful, I like this post

  • Sham Haramalkar

    How to do ‘On page refresh, load the previous pages’ ?

  • Ahmad

    Thank you for this Code , but i have a problem and i dont know what to do if you please help me with it i really need to do this infinite scroll πŸ™‚

    Error 1 Could not load type ‘CSASPNETInfiniteLoading_Default’.

  • Armagan

    Very nice script especially classic ASP I have not more one. Only problem is most of the asp user using Mssql or ms access not Mysql. How can adapt to mssql I did not find. Because no Limit function in MSSQL. Select TOP …. not same. Do you have a solution for mssql

  • albert

    The reason why it’s not working on chrome or opera is this javasscript

    if ($(window).scrollTop() >= $(document).height() – $(window).height())

    that script don’t recognize by chrome or opera

    use $_SERVER[“HTTP_USER_AGENT”] to block that script when users using chrome or opera

    $(window).scroll(function(){

    lastPostFunc();

    });

    I manage to make it work and my shopping cart works fine hell yeah πŸ˜€

    thanks for sharing this script i really need this badly

  • MJ

    I managed to get this work to display new content on my page but it is very very fussy with font tags. If I open a font tag I have to close it otherwise I get an error in IE (it will not load new data and just display the circle endlessly). Not a big deal but somewhat annoying.

Search