This plugin aims to progressively enhance your page. Your navigation/pagination elements should be present in the HTML for non-js users, but the plugin will utilize those links to build out a more rich browsing experience.
Download the jQuery plugin
Version 1.5.100504
jquery.infinitescroll.js and minified are now on GitHub
Usage
Minimum required configuration
This is the minimum amount of configuration you can do, if you want things to work:
// infinitescroll() is called on the element that surrounds // the items you will be loading more of $('#content').infinitescroll({ navSelector : "div.navigation", // selector for the paged navigation (it will be hidden) nextSelector : "div.navigation a:first", // selector for the NEXT link (to page 2) itemSelector : "#content div.post" // selector for all items you'll retrieve });
All options
// usage: // $(elem).infinitescroll(options,[callback]); // infinitescroll() is called on the element that surrounds // the items you will be loading more of $('#content').infinitescroll({ navSelector : "div.navigation", // selector for the paged navigation (it will be hidden) nextSelector : "div.navigation a:first", // selector for the NEXT link (to page 2) itemSelector : "#content div.post", // selector for all items you'll retrieve debug : true, // enable debug messaging ( to console.log ) loadingImg : "/img/loading.gif", // loading image. // default: "http://www.infinite-scroll.com/loading.gif" loadingText : "Loading new posts...", // text accompanying loading image // default: "<em>Loading the next set of posts...</em>" animate : true, // boolean, if the page will do an animated scroll when new content loads // default: false extraScrollPx: 50, // number of additonal pixels that the page will scroll // (in addition to the height of the loading div) // animate must be true for this to matter // default: 150 donetext : "I think we've hit the end, Jim" , // text displayed when all items have been retrieved // default: "<em>Congratulations, you've reached the end of the internet.</em>" bufferPx : 40, // increase this number if you want infscroll to fire quicker // (a high number means a user will not see the loading message) // new in 1.2 // default: 40 errorCallback: function(){}, // called when a requested page 404's or when there is no more content // new in 1.2 localMode : true // enable an overflow:auto box to have the same functionality // demo: http://paulirish.com/demo/infscr // instead of watching the entire window scrolling the element this plugin // was called on will be watched // new in 1.2 // default: false },function(arrayOfNewElems){ // optional callback when new content is successfully loaded in. // keyword `this` will refer to the new DOM content that was just added. // as of 1.5, `this` matches the element you called the plugin on (e.g. #content) // all the new elements that were found are passed in as an array });
Custom trigger, non-automatic. Twitter-style
In 1.4 you can trigger the loading of the next page of content at will. You’ll first unbind the default behavior. And then trigger the next pull whenever you like..
// unbind normal behavior. needs to occur after normal infinite scroll setup. $(window).unbind('.infscr');
// call this whenever you want to retrieve the next page of content // likely this would go in a click handler of some sort $(document).trigger('retrieve.infscr');
Demo of the triggered infinite scroll functionality.
How does it work?
There is a little known feature in the .load() method that lets you specify the CSS selector of the html you want to include. jQuery will load in any local URL, then parse the html and grab only the elements you’ve defined with your selector. This allows for some pretty fun shit: client-side transclusions (a la purple include) ; and some really kickass shit when you combo it with a local php proxy.
This is really the meat of the code:
// load all post divs from page 2 into an off-DOM div $('<div/>').load('/page/2/ #content div.post',function(){ $(this).appendTo('#content'); // once they're loaded, append them to our content area });
So it basically leverages that load() method at its core. It’s basically scraping your existing page structure, which means you don’t need to code any custom backend stuff to enable this functionality! Booyah, right?
Thanks, this blog aided me in solving some issues with the latest version, Why do they always seem to leave out vital information when they upgrade? It may be trivial to them but not for us! I’m sure i’m not alone either.
this is awesome!
just wondering if the callback will still happen if I call $(document).trigger(’retrieve.infscr’) because it doesn’t seem to — is this the same as @shamot’s problem
Can it work like Yahoo Mail (not like Google Reader)?
What I mean is — can it show the real height of the scrollbar before loading the content?
I’ve removed the fadeout animation from the Done Text.
However…
When I hit the end, go to another page and then go back– the Done Text has disappeard. Any ideas?
Just wondering, has anyone had any luck getting this working on an iPhone or iPad. I have it working fine in all computer browsers but just can’t get it working on the 2 Apple devices.
Before i spend time trying to fix it it just thought I see if it was even possible. Any pointers would be appreciated.
Thanks.
just wondering if the callback will still happen if I call $(document).trigger(’retrieve.infscr’) because it doesn’t seem to
i have code as follows but nothing happens …
$(function() {
$(”.posts”).infinitescroll({
navSelector: “#pageNav”,
nextSelector: “.next”,
itemSelector: “.posts .post”
});
});
…
…
…
1
2
3
4
5
on a side note, what happens if the HTML navigation only has the class .active on the active link, and i dont have a .next class?
I love this plugin and have implemented it on my latest project: http://www.icusawme.com
I would like to make the time that donetext is displayed longer. Is there a way to do this through configuration or do I have to dig into the library code?
You’ll have to dig into the the library code.
http://github.com/paulirish/infinite-scroll/blob/master/jquery.infinitescroll.js#L99
Change the 2000 to a bigger number. :)
G’luck!
Its almost too easy. I had the minified version, it was much harder to find the line there. Thanks Paul!
When uses the non-auto and click twice (like double click) returns:
["math:", 300, 871]
["heading into ajax", ["http://localhost/Transfer/Site/page/", "/"]]
GET http://localhost/Transfer/Site/page/2/ | 200 OK | 438ms
["heading into ajax", ["http://localhost/Transfer/Site/page/", "/"]]
GET http://localhost/Transfer/Site/page/3/ | 200 OK | 385ms
["Page not found. Self-destructing..."]
good site!
Hi,
I am loading images by making FLickr API call and populating images in div named Flickr_Container(using PHP), The number of images uploaded have exceeded my expectation and now I want to use infinite scroll for displaying images. Basically on page load I like to display 90 images and then as user scrolls down, I like to display next 90 and so on till we reach at the end. Can you help me in implementing infinite scroll for my purpose.
Thanks a lot
<a href=”" rel=’lightbox’><img src=”" width=”75″ height=”75″ />
Hi,
I am loading images by making FLickr API call and populating images in div named Flickr_Container, The number of images uploaded have exceeded my expectation and now I want to use infinite scroll for displaying images. Basically on page load I like to display 90 images and then as user scrolls down, I like to display next 90 and so on till we reach at the end. Can someone help me in implementing infinite scroll for my purpose
<a href=”" rel=’lightbox’><img src=”" width=”75″ height=”75″ />
Success usually comes to those who are too busy to be looking for it- Henry David Thoreau (1817-1862)
Hi Paul - thank you so much for an incredible script -
I just wish I could get it to work.
I am trying to get it to work with Masonry on an Expression Engine site (which is using Structure - so it is generating URLs that go page=2 page=3 etc - so I don’t think this is the same issue that Matt Jones had above).
The site build can be seen here:
http://printclublondon.com/alpha/index.php/news
I think i’ve got everything wrapped up correctly - but it isn’t picking up the IR script… if you are able to cast your eye over it and let me know if anything jumps out that would be incredible -
All the best
James
Thanks for the email Paul - works a treat now -
In case anyone else has the same issue - I hadn’t named the hooks for the script correctly - which paul pointed out that (in my case - because of the way expression engine with structure spits out the pagination link) should be:
navSelector is .pagination
nextSelector is .next a
Thank you -
James
Hi, I want to let all of you bloggers / web users recognize about a fresh Search Engine called Braxea. Its pretty dam cool… It combines Google, Bing and Yahoo into one plus lets you search for videos on YouTube and News throughout the net. Maybe this will become the new Google ?
Hey, i have a problem, my paging system is /page/2 to /page/40/ and it doesn’t seem to work. Every page should give another 5 entries, but it just displayes the first page entries and when i scroll to the bottom of those 5 entries it will say “Congratulations, you’ve reached the end of the internet.”
Do you know what might be the problem? I’m figuring it’s my side…
curious why at the end of the scroll it loads a ton of 404s? Is there something I can do to stop that? Saw a note about “my theme” not being capable. but then there’s no note on how TO make it capable.
Thanks.
This works great - sometimes your nav is inside the content div so just add a around your next and previous in your php. Works flawlessly!
Hello,
I have the same problem as Paul. I am only able to load the 1st page but I can’t seem to get to the other pages when I reach the end of page 1.
The example is at v2.thomasjurdi.com/photos.html.
What do I need to add to page 1 to have automatically load page 2 at the end apart from the next item selector which is the same as the one used in page 0 to load page 1?
Thank you for the help. Much appreciated.
[...] 最开始是从jinwen的Js O4w主题上看到这个效果,不过我看了源代码,他只是用了三层获取,就是做三个more.php文件用来响应三次点击事件,并不是真正的无限分页,而且实现起来比较麻烦。找了很久,最近发现了一个infinite-scroll,同时提供了实现这个效果的wordpress插件以及JQuery插件。看了一下,其实wordpress插件原理都是一样,设置也比较麻烦,还不如直接上js来的直接,原文是英语的,转过来:Infinite Scroll jQuery Plugin [...]
it is great when it works.
I am not sure but I think it works when the pages have sequence names like page1, page2, page3.
When the sequence breaks, it does not work.
please confirm if I am right.
Tranks!
http://www.tvbrasil.org.br/novidades/
thanks*
Good job!
Wow! Just what I was looking for. It seems every other scroller only wanted to add static content. At least this scrapes the page it loads so I can just pass arguments to the page im requesting. :) Awesome post!
-M
Hi Paul,
first of all thank for this great plugin. It works beautifully, unfortunately I can’t get it to work with masonry. I am using your Wordpress plugin.
I load masonry first:
`
jQuery(document).ready(function() {
jQuery(’#content’).masonry({ singleMode: true, columnWidth: 192, itemSelector: ‘.box’ });
});
`
First page of content loads and is arranged by masonry, then the Infinite Scroll kicks in and loads the rest of content, which then isn’t affected by masonry. I tried inserting this:
` function( newElements ) {
$(this).masonry({ appendedContent: $( newElements ) });
}`
…but it stops Infinite Scroll completely. What am I doing wrong? Would you be able to point me in the right direction?
Thanks so much!
Hi Paul,
It’s really INFINITE in my install. The last-item loaded content is loaded again and again and never just stops. So I wonder if I can add some callback function to compare that the requested URL matches the last item URL, then stop the scroll if they match. Please kindly tell me how I would accomplish that?
This is the code I have now:
$(selector).infinitescroll({some settings},function(currPage){
if (currPage == $(’.pager-last a’).attr(’href’) ) {
$(window).unbind(’.infscr’);
return;
}
});
This does nothing. So what I need I guess is the correct currPage, or redefined currPage, perhaps?
Thanks for any possible hint.
Here is a patch to the jquery version which does not try to guess/calculate the next page, but actually reads it from the the next link from the content returned from ajax. It also does not load the next loaded page into a element (thus preventing the execution of included javascript tags until later and preventing other possible events to trigger) but keeps it only in the context of the method ‘loadCallback’
—-
Index: jquery.infinitescroll.js
===================================================================
@@ -32,31 +32,7 @@
function determinePath(path){
path.match(relurl) ? path.match(relurl)[2] : path;
- return path;
- // there is a 2 in the url surrounded by slashes, e.g. /page/2/
- if ( path.match(/^(.*?)\b2\b(.*?$)/) ){
- path = path.match(/^(.*?)\b2\b(.*?$)/).slice(1);
- } else
- // if there is any 2 in the url at all.
- if (path.match(/^(.*?)2(.*?$)/)){
-
- // page= is used in django:
- // http://www.infinite-scroll.com/changelog/comment-page-1/#comment-127
- if ( path.match(/^(.*?page=)2(\/.*|$)/) ){
- path = path.match(/^(.*?page=)2(\/.*|$)/).slice(1);
- return path;
- }
-
- debug(’Trying backup next selector parse technique. Treacherous waters here, matey.’);
- path = path.match(/^(.*?)2(.*?$)/).slice(1);
- } else {
-
- // page= is used in drupal too but second page is page=1 not page=2:
- // thx Jerod Fritz, vladikoff
- if (path.match(/^(.*?page=)1(\/.*|$)/)) {
- path = path.match(/^(.*?page=)1(\/.*|$)/).slice(1);
- return path;
- }
+ if (path.length==0) {
debug(’Sorry, we couldn\’t parse your Next (Previous Posts) URL. Verify your the css selector points to the correct A tag. If you still get this error: yell, scream, and kindly ask for help at infinite-scroll.com.’);
props.isInvalidPage = true; //prevent it from running on this page.
@@ -71,7 +47,7 @@
// weird doubletouch of scrollheight because http://soulpass.com/2006/07/24/ie-and-scrollheight/
return opts.localMode ? ($(props.container)[0].scrollHeight && $(props.container)[0].scrollHeight)
// needs to be document’s height. (not props.container’s) html’s height is wrong in IE.
- : $(document).height()
+ : $(document).height();
}
@@ -136,12 +112,11 @@
box = $(opts.contentSelector).is(’table’) ? $(”) : $(”);
frag = document.createDocumentFragment();
-
- box.load( path.join( props.currPage ) + ‘ ‘ + opts.itemSelector,null,loadCallback);
+ $.get(path,loadCallback);
}
- function loadCallback(){
+ function loadCallback(box){
// if we’ve hit the last page…
if (props.isDone){
showDoneMsg();
@@ -149,21 +124,21 @@
} else {
- var children = box.children().get();
-
+ var children = $(opts.itemSelector,box).children().get();
+ // console.log(children);
// if it didn’t return anything
if (children.length == 0){
// fake an ajaxError so we can quit.
return $.event.trigger( “ajaxError”, [{status:404}] );
}
-
- // use a documentFragment because it works when content is going into a table or UL
- while (box[0].firstChild){
- frag.appendChild( box[0].firstChild );
- }
- $(opts.contentSelector)[0].appendChild(frag);
+ $(opts.itemSelector).append(children);
+ path = $(opts.nextSelector,box).attr(’href’);
+
+ if (!path) { showDoneMsg();
+ return false; }
+ path = determinePath(path);
// fadeout currently makes the ‘d text ugly in IE6
props.loadingMsg.fadeOut(’normal’ );
@@ -235,6 +210,7 @@
// set up our bindings
$(document).ajaxError(function(e,xhr,opt){
+
debug(’Page not found. Self-destructing…’);
// die if we’re out of pages.
—-
if this doesn’t work, i am glad to provide the whole script.
cheers Frank
Frank, could you please provide a link. It is so hard to read it from the comment.
Hi sorry, didn’t check back in time :)
i posted it here:
http://taka-its.com/infinite/jquery.infinitescroll.js.patch
and here the complete patched plugin:
http://taka-its.com/infinite/jquery.infinitescroll.js
cheers
Frank
Hi, I used the infinite scroll and it works on all browsers but Opera. I don’t know why but if you click on a link it should scroll softly to the linked position (i got a one-page layout), but the “scroll event” starts at the top of the page and scrolls down to the linked position. It seems that in Opera the script doesn’t scroll from the actual position but always from the top of the page. Maybe you should take a look on the problem http://dennissiegel.de
I really have no idea what to do. If the problem can’t be solved I need to use another script, if available. BUT I WONT! infinite scroll is good - but not in Opera. Help me, please!
Dennis
One of my clients has a Microsoft SQL 2005 database for his gallery. Still using Classic ASP. He wants to create a thumbnail gallery with infinite scroll. Are there any Infinite Scroll examples around that use database integration ?
Seems that the Infinite Scroll jQuery plug-in doesn’t work when you change the “container” from the window to a DIV. While localMode has been replaced by the “container” attribute, that attribute doesn’t work right (doesn’t seem to work in the examples in the download bundle either).
Am I doing something wrong, or is this something that can be fixed easily?
(addendum: Lines 270-272 bind the scroll to the window always, but never to the “container”; hence the problem?)
Great post! Maybe you could do a follow up on this topic :P
I’m with Hans, doesnt seem to work on a div anymore.
not working on iphone. anyone else experiencing same problem?
@sergey, yup.. iphone is a known bug.
https://github.com/paulirish/infinite-scroll/issues#issue/3
Hey great script! I was wondering if it is possible to specify a different file names for the subsequent pages (trigger2.html and trigger3.html etc..). I would like to use 1 php page over and over again that is passed a parameter to change its loaded posts from a database.
Any way of doing this??
Thanks
Hello -
I can’t get this plugin to work with the latest Wordpress version 3.0.4. Seems I’m not the only one…
Is there a fix / upgrade for 3.0.4 ?
Thanks!
[...] Status 上 InfiniteScroll 的插件没有人维护~ 但 Infinite Scroll 的作者更新了代码~ 反正 StatusNet 里现在自带的代码是很古老的了…… [...]
Hey there,
I’ve added infinite scroll to my website, all with great success so far. It’s running on cakephp and works flawlessly with the pagination that framework has, so thanks for that.
The only problem is… any javascript on the pages fetched through ajax (page2, 3,…) is gone. I’m sure this is some kind of escape: false setting somewhere, but i can’t seem to find it :( any ideas?
thanks!
alright, not to spam, but i’ve pinpointed this problem to the .load method of jquery.
in infinite-scroll, this takes care of the loading:
https://github.com/paulirish/infinite-scroll/blob/master/jquery.infinitescroll.js#L161
apparently, if .load is executed with a selector (box in this case), it uses the html method and strips all script tags. have a look at the jquery 1.4.4 developer source (http://code.jquery.com/jquery-1.4.4.js) and search for this line:
“complete: function( res, status )”
this is the function that is called when the content is fetched. you’ll see that, if a selector was used, it executes a replace on script tags, apparently causing a security problem in IE. apparently, you’d have to use the jquery getscript method to get the script after the other content was loaded. which sucks of course, because i have a script tag after every post. i could of course set my pagination to 1, which would load just enough posts at the beginning, to fill the screen i guess, but it would probably kill my server with requests…
[...] tenemos a disposición el plugin para jQuery Infinite Scroll que con un mínimo de opciones a configurar nos permite lograr el efecto en cualquier [...]
Have you checked out eval ajax response?
Hi! How can I change the delay time before jQuery upload the new posts?
My infinite scrolling only starts on page two. any idea how to solve it? it’s really making me upsep. :(
hi, is it possible to fire code when the elements of an appended page have finished loading? i’ve tried david desandro’s solution for tumblrs using masonry but it was really clumsy for image-heavy tumblrs. thanks for any advice!