Infinite Scroll Using Ajax by Manideep | JavaScriptSource

Infinite Scroll Using Ajax by Manideep

Manideep Feb 1, 2016

Abstract

Instead of showing results in different pages, retrieving all the results in a single page using simple JavaScript code.

Description

An infinite-content page can be achieved by adding a scene that triggers at the bottom of the page. On Scene start enter loading state. Save the state to prevent multiple triggers. In this example the class of the #loader element is used. Make ajax call to load additional content (if not already in loading state). When receiving the ajax "load" event, add the content to your container, update the scene and revert to original state. The demo below doesn't really use ajax to ensure offline compatibility. Instead it uses a function to imitate an ajax call to add content.

Code Snippet

<script>
//init controller
var controller = new ScrollMagic.Controller({triggerElement: ".dynamiccontent #loader", triggerHook: "onEnter"})
.addTo(controller)
.on("enter", function (e)
{
if(!$("#loader").hasClass("active")){
$("#loader").addClass("active");
if(console){
console.log("loading new items");
}
//simulate ajax call to add content using  the function below
setTimeout(addBoxes, 1000, 9);
}
});
//pseudo function to add new content . In real life it would be done through an ajax request.
function addBoxes(amount){
for (i=1;i<=amount;i++){
var randomColor = '#'+ ('00000'+(Math.random())*0xFFFFFF<<0).toString(16)).slice(-6);
$("<div></div>")
.addClass("box1")
.css(background-color, randomColor)
.appendTo(".dynamicContent #content");
}
//loading dont -> revert to normal state
scene.update();//make sure the scene gets the new start position
$("#loader").removeClass("active");
}
//add some boxes to start with
addBoxes(18);
</script>

Leave a Response

(1 comment)

there's an error in var = randomColor ... .toString(16)) must be toString(16) and maybe other and missing some description

pippo Aug 30, 2016