DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
Securing Your Software Supply Chain with JFrog and Azure
Register Today

Trending

  • Event-Driven Architecture Using Serverless Technologies
  • Constructing Real-Time Analytics: Fundamental Components and Architectural Framework — Part 2
  • RBAC With API Gateway and Open Policy Agent (OPA)
  • Tech Hiring: Trends, Predictions, and Strategies for Success

Trending

  • Event-Driven Architecture Using Serverless Technologies
  • Constructing Real-Time Analytics: Fundamental Components and Architectural Framework — Part 2
  • RBAC With API Gateway and Open Policy Agent (OPA)
  • Tech Hiring: Trends, Predictions, and Strategies for Success
  1. DZone
  2. Data Engineering
  3. Data
  4. Infinite Scroll Example with ColdFusion

Infinite Scroll Example with ColdFusion

Raymond Camden user avatar by
Raymond Camden
·
May. 23, 13 · Interview
Like (0)
Save
Tweet
Share
3.05K Views

Join the DZone community and get the full member experience.

Join For Free

A few weeks ago a reader asked if I had an example of infinite scroll with a ColdFusion back end. I replied that I did not, and that infinite scroll was the worst thing to happen to the Internet since the rainbow horizontal rule.

I'm possibly being a bit overly dramatic, but I'm really not a fan of it. Maybe it's the OCD in me, but the fact that I can never get to the end of an infinite scroll UI just bugs the hell out of me.

That being said - I figured - why not make a quick example. It can't hurt, right?

I did some Googling on the topic. Initially the results I found were not very helpful. Many required a bit of configuration and I was really looking for something quick and simple. Finally I came across this great answer on Stack Overflow:

$(window).scroll(function () { 
   if ($(window).scrollTop() >= $(document).height() - $(window).height() - 10) {
      //Add something at the end of the page
   }
});

4 simple lines. Nice! So I took this and ran with it. I first created a fake service in a ColdFusion component that would return an infinite amount of data. Not exactly real world, but it worked. Note that I added a bit of a delay to the code so that my local testing would feel a bit more realistic.

component {

  //default per page
	variables.perpage = 25;

	//json all the things
	url.returnformat = "json";

	remote function getData(numeric start = 1) {
		//fake slowness
		sleep(1000);
		var results = [];
		for(var i=1; i <= variables.perpage; i++) {
			var result = { "title":"This Is Blog #start+i-1#", "body": repeatString("This is some random stuff. ", randRange(3,7)) };
			arrayAppend(results, result);
		}

		return results;

	}


}

The code here is pretty arbitrary. I return an array of structures containing a title and a body. I accept a start parameter, but I don't really even use it. Again, the entire purpose for this was to just send me a lot of data. Now let's look at the front-end code.

<!doctype html>
<html lang="en">
  <head>
		<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
		<script>
			$(document).ready(function() {
				
				//flag to detect already loading
				var loading = false;
				//initial position
				var position = 1;
				//a place for my crap
				var contentDiv = $("#content");
				
				//populate the initial content
				loadContent(position);
				
				$(window).scroll(function () { 
					if ($(window).scrollTop() >= $(document).height() - $(window).height() - 10) {
						loadContent(position);
					}
				});
				
				function loadContent(s) {
					if(loading) return;
					loading = true;
					
					contentDiv.append("<span class='loading'>Loading...</span>");
					$.get("service.cfc?method=getData", {start:position}, function(res, code) {
						//Lame dynamic output
						var s = "";
						for(var i=0, len=res.length; i<len; i++) {
							s += "<h2>" + res[i].title + "</h2><p> " + res[i].body + "</p>";
						}
						contentDiv.find(".loading").remove();
						contentDiv.append(s);
						
						position += res.length;
						loading = false;
					},"json");
					
					
				}
				
			})
		</script>
	</head>
	
	<body>
		
	<div id="content"></div>
		
	</body>
</html>

A bit more than 4 lines, but hopefully you will see that I've simply taken the logic from the Stack Overflow answer and wrapped it around a call to a function called loadContent. loadContent handles several things.

  • First, it is intelligent enough to recognize when it is fetching data and prevent you from making multiple XHR requests at once.
  • Secondly, it handles updating the DOM with a loading message so you know important crap is on the way.
  • It does the XHR call and handles rendering it out. (Insert reminder about using JavaScript templates here.)
  • Finally it removes the loading message.

Overall, pretty simple. You can demo this here: http://www.raymondcamden.com/demos/2013/may/21/test.html. If it seems slow, remember that I kept in that sleep() command there.

I built a second demo that makes use of my actual blog database. For the most part it is the same, but note the use of a Query and limit operations to page the data.

component {

  //default per page
	variables.perpage = 25;

	//json all the things
	url.returnformat = "json";

	remote function getData(numeric start = 1) {
		var q = new com.adobe.coldfusion.query();
		q.setDatasource("myblog");
		q.setSQL("select title, posted, left(body,250) as excerpt from tblblogentries order by posted desc limit #val(arguments.start)-1#,20");
		var rows = q.execute().getResult();

		var results = [];
		for(var i=1; i<=rows.recordCount; i++) {
			arrayAppend(results, {"title":rows.title[i], "posted":rows.posted[i],"excerpt":htmlEditFormat(rows.excerpt[i])});
		}

		return results;

	}


}

You can demo this version here: http://www.raymondcamden.com/demos/2013/may/21/test2.html

In my testing this downloaded pretty quick (and I'm on VPN now downloading 2 gigs of VMs). There are two things missing from this version.

One - I need to enable my front-end service to recognize when it is no longer getting rows of data from the back end. I could handle that with a flag in the result object or some other way.

Second - If I were to add links to the actual blog entries, I'd need to support some way of remembering where you were when you hit the back button.

If folks care, I'll do some updates to add that.

Data (computing) Database Stack overflow Overflow (software) Blog Template IT

Published at DZone with permission of Raymond Camden, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Trending

  • Event-Driven Architecture Using Serverless Technologies
  • Constructing Real-Time Analytics: Fundamental Components and Architectural Framework — Part 2
  • RBAC With API Gateway and Open Policy Agent (OPA)
  • Tech Hiring: Trends, Predictions, and Strategies for Success

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com

Let's be friends: