How to Create an Infinite Scrolling Web Gallery

How to Create an Infinite Scrolling Web Gallery

When working my way through a web gallery, I find it annoying when I must change pages; so in today’s tutorial, we will learn how to create an auto-generating, one-page, infinite scrolling gallery with PHP and AJAX. Let’s get started!


Step 1: Project Outline

We’ll begin with a normal gallery page that has a container for our images, and we’ll monitor the scroll position by calling a JavaScript function at a quick interval. Each time the scroll bar is near the bottom, we’ll make an AJAX request to an external PHP file, which returns a list of image names. Now, all we’ll need to do is add these images to our container, thus modifying the page height moving the scroll position higher.


Step 2: HTML Markup

We’ll work with a very basic setup: a header and the container for our images. The thumbnails will be grouped in sets of three rows, each will contain a link, referencing the full size image. After each group, we will add some text showing the total number of displayed images, and a link to the top of the page.

<body>
	<div id="header">Web Gallery | Infinite Scroll</div>
	<div id="container">
		<a href="img/Achievements.jpg"><img src="thumb/Achievements.jpg" /></a>
		<a href="img/Bw.jpg"><img src="thumb/Bw.jpg" /></a>
		<a href="img/Camera.jpg"><img src="thumb/Camera.jpg" /></a>
		<a href="img/Cat-Dog.jpg"><img src="thumb/Cat-Dog.jpg" /></a>
		<a href="img/CREATIV.jpg"><img src="thumb/CREATIV.jpg" /></a>
		<a href="img/creativ2.jpg"><img src="thumb/creativ2.jpg" /></a>
		<a href="img/Earth.jpg"><img src="thumb/Earth.jpg" /></a>
		<a href="img/Endless.jpg"><img src="thumb/Endless.jpg" /></a>
		<a href="img/EndlesSlights.jpg"><img src="thumb/EndlesSlights.jpg" /></a>    

		<p>9 Images Displayed | <a href="#header">top</a></p>
	    <hr />
	</div>
</body>

Step 3: CSS

The CSS is also quite basic. First, we define the page colors and positioning for the header and paragraphs.

body{
	background:#222;
	color:#666;
}
#header{
	font-family:Arial, Helvetica, sans-serif;
	font-size:24px;
	font-weight:bold;
	text-align:left;
	text-indent:35px;
	margin: 0 auto;
	width:800px;
	margin-bottom:10px;
}
hr{
	margin: 20px;
	border:none;
	border-top: 1px solid #111;
	border-bottom: 1px solid #333;
}
p{
	color:#444;
	text-align:left;
	font-size:10px;
	margin-left: 20px;
	margin-bottom: -10px;
}
a{
	color:#444;
}

Step 4

Then, for the container and images, I used a bit of CSS3 to add round corners and shadows. Don’t forget "-moz-box-shadow" and "-moz-border-radius" for Firefox and "-webkit-box-shadow" and "-webkit-border-radius" for Chrome and Safari.

#container{
	margin: 0 auto;
	width:800px;
	border:1px solid #333;
	-moz-border-radius: 10px;
	-webkit-border-radius: 10px;
	font-family:Verdana, Geneva, sans-serif;
	text-align:center;
}
img{
	border:10px solid #444;
	-moz-border-radius: 5px;
	-webkit-border-radius: 10px;
	margin: 15px;
}
img:hover{
	border-color:#555;
	-moz-box-shadow: 0px 0px 15px #111;
	-webkit-box-shadow: 0px 0px 15px #111;
}

Step 5: PHP Script

This is going to be very short. We need to call the PHP script with the index of the next image we need as a parameter. First of all, we have to retrieve all the available image names from a directory and save them into an array. I organized my images in two folders: "thumb" and "img" which contain the thumbnails and actual images, respectively. Note that the thumbnails must have the exact same name as their corresponding full size images.

<?php

$dir = "thumb";
if(is_dir($dir)){
	if($dd = opendir($dir)){
		while (($f = readdir($dd)) !== false)
			if($f != "." && $f != "..")
				$files[] = $f;
	closedir($dd);
	} 

We define a variable for the directory we want to get the image names from, test if it exists, and if we can open it, read all the file names from it. When reading an entire folder, we will always get two extra elements we may not want: "." – this stands for the current directory, and ".." – this stands for the parent directory. To compensate, we have to test if the element read is different from these two, then we can safely add it to our array.

$files[] = $f;

As a note, when adding an element to an array and not specifying the position to be placed in, it will always push the element to the end of the array.


Step 6

Now we have to build our response text. We are going to send back to the JavaScript a single string containing all the necessary file names separated by a semi-colon.

	$n = $_GET["n"];
	$response = "";

We get the URL parameter for the index of the next image we need, and we initialize our response text.

	for($i = $n; $i<$n+9; $i++)
		$response = $response.$files[$i%count($files)].';';
	echo $response;
}
?>

As I said before, the images will be grouped in sets of three rows, each containing three images, so we only need nine images to return the file names for a group. We start at the index we got as parameter, $n, and go until $n+9. At each increment, we add our image name followed by ";" to the response text. Here is a little tricky part. We won’t have an infinite number of images; so in order to create the effect of an "infinite" gallery which never ends, each time the index of the next image is greater that the total number of images, we must start over from the beginning. This is done by applying the "modulo" or "%" function between the index and the total number of images.

	$i%count($files)

As a result, we get the remainder of the division between these two elements. For example, if the index "$i" is "50" and the number of images "count($files)" is "45" the result will be "5". As well, if "$i" is "50" and "count($files)" is "65", the result will be "50". Finally, we have to send back our response text.


Step 7

Here is the complete PHP script. Just place your completed code within a new .php file.

<?php

	$dir = "thumb";
	if(is_dir($dir)){
		if($dd = opendir($dir)){
			while (($f = readdir($dd)) !== false)
				if($f != "." && $f != "..")
					$files[] = $f;
			closedir($dd);
		} 

	$n = $_GET["n"];
	$response = "";
		for($i = $n; $i<$n+9; $i++){
			$response = $response.$files[$i%count($files)].';';
		}
		echo $response;
	}
?>

Step 8: JavaScript

As usual, first we define some variables we will need later on.

var contentHeight = 800;
var pageHeight = document.documentElement.clientHeight;
var scrollPosition;
var n = 10;
var xmlhttp;

In order to determine weather the scroll bar is near the bottom of the page, we need three variables:

  • "contentHeight" – the height of the initial gallery
  • "pageHeight" – the height of the visible page in the browser
  • "scrollPosition" – the position of the scroll bar measured from the top

Lastly, we need a variable for the next image index (which we are going to send to the PHP script), and a variable for the Ajax request object.


Step 9

We need to define a function that will add the images to our HTML container.

function putImages(){
	if (xmlhttp.readyState==4){
    	if(xmlhttp.responseText){

A request object goes through different states as the request is made, each of which has a numerical value associated. The one we are interested in is the final state, when the request is complete and the value is "4". We first test if the request is in this state, and then check to see if we received a response.


Step 10

If both conditions are fulfilled, we have to tokenize the response text. This means we have to separate the file names into an array. Remember that in the PHP script we returned a single string with the names separated by semi-colons. Here is an example: Achievements.jpg;Bw.jpg;Camera.jpg;Cat-Dog.jpg;CREATIV.jpg;creativ2.jpg;Earth.jpg;Endless.jpg;EndlesSlights.jpg;

var resp = xmlhttp.responseText.replace("\r\n", "");
var files = resp.split(";");

There is a bit of a problem we have to deal with first; the response text may have at the beginning a new line character which we do not want. This is easily fixed with the "replace" function, that takes two parameters: "\r\n" – the new line character, and "" – empty string that will replace all occurrences of the first parameter. Now all we have to do is to split the string by our delimiter ";".


Step 11

Next, we have to add the images to our container.

            var j = 0;
            for(i=0; i<files.length; i++){
                if(files[i] != ""){
                    document.getElementById("container").innerHTML += '<a href="img/'+files[i]+'"><img src="thumb/'+files[i]+'" /></a>';
                    j++;

                    if(j == 3 || j == 6)
                        document.getElementById("container").innerHTML += '';
                    else if(j == 9){
                        document.getElementById("container").innerHTML += '<p>'+(n-1)+" Images Displayed | <a href='#header'>top</a></p><hr />";
                        j = 0;
                    }
                }
            }

For every element in our array, we check if it isn’t an empty string, and add the thumbnail with the link on it. We have to keep a counter "j" in order to separate the images in rows. After every third and sixth thumbnail added, we create a new line, and after nine thumbnails added we put the text showing the total number of displayed images and a link to the top of the page.


Step 12

Here is the complete function.

function putImages(){
	if (xmlhttp.readyState==4){
    	if(xmlhttp.responseText){
			var resp = xmlhttp.responseText.replace("\r\n", "");
			var files = resp.split(";");

            var j = 0;
            for(i=0; i<files.length; i++){
                if(files[i] != ""){
                    document.getElementById("container").innerHTML += '<a href="img/'+files[i]+'"><img src="thumb/'+files[i]+'" /></a>';

                    j++;
                    if(j == 3 || j == 6)
                        document.getElementById("container").innerHTML += '';
                    else if(j == 9){
                        document.getElementById("container").innerHTML += '<p>'+(n-1)+" Images Displayed | <a href='#header'>top</a></p><hr />";
                        j = 0;
                    }
                }
            }
		}
	}
}

Step 13

Now we are going to define the function that will check if the scroll position is getting near the bottom, and makes the request to the server.

function scroll(){

	if(navigator.appName == "Microsoft Internet Explorer")
		scrollPosition = document.documentElement.scrollTop;
	else
		scrollPosition = window.pageYOffset;

First, we have to find the position of the scroll bar. Internet Explorer does this a bit differently, so we have to determine what browser the client is using, then just store the value in the variable we defined earlier.


Step 14

	if((contentHeight - pageHeight - scrollPosition) < 500){

Now we check to see if we are about to reach the end of our gallery – if the part of the page visible in the browser is below the bottom 500px of the entire page. This isn’t an exact value, you may use a different one if you find it suitable. If this condition is true, we can continue on and add new images.


Step 15: Creating the XMLHttpRequest Object

We are ready to make the XMLHttpRequest object and send it. Again, for Internet Explorer the definition is a bit different, so we must compensate for this as well.

	if(window.XMLHttpRequest)
			//Firefox, Opera, Safari
			xmlhttp = new XMLHttpRequest();
		else
			if(window.ActiveXObject)
            	//Internet Explorer
				xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
			else
				alert ("Bummer! Your browser does not support XMLHTTP!");

Step 16

Before sending the request, we have to specify the PHP script name on the server and insert the parameters we want to give it.

	var url="getImages.php?n="+n;

This is a simple text variable representing the URL of the page.


Step 17

It’s time to send the request.

		xmlhttp.open("GET",url,true);
		xmlhttp.send();

The URL is set by calling the "open" method. The second parameter is the important one, this being the script’s URL. After doing so, all we need is to send it. This will run the PHP script and put in "xmlhttp.responseText" the return value of it.


Step 18

The final step is to place the new content on the page by calling the function we defined earlier "putImages" and to prepare our variables for the next request.

		n += 9;
		contentHeight += 800;
		xmlhttp.onreadystatechange = putImages;
	}
}

We have nine new images in the gallery, so we increment "n" with 9, and we need to change the page height; so increment "contentHeight" with 800.


Step 19

Here is the entire JavaScript we’ve used.

<script>
var contentHeight = 800;
var pageHeight = document.documentElement.clientHeight;
var scrollPosition;
var n = 10;
var xmlhttp;

function putImages(){

	if (xmlhttp.readyState==4)
	  {
		  if(xmlhttp.responseText){
			 var resp = xmlhttp.responseText.replace("\r\n", "");
			 var files = resp.split(";");
			  var j = 0;
			  for(i=0; i<files.length; i++){
				  if(files[i] != ""){
					 document.getElementById("container").innerHTML += '<a href="img/'+files[i]+'"><img src="thumb/'+files[i]+'" /></a>';
					 j++;

					 if(j == 3 || j == 6)
						  document.getElementById("container").innerHTML += '';
					  else if(j == 9){
						  document.getElementById("container").innerHTML += '<p>'+(n-1)+" Images Displayed | <a href='#header'>top</a></p><hr />";
						  j = 0;
					  }
				  }
			  }
		  }
	  }
}

function scroll(){

	if(navigator.appName == "Microsoft Internet Explorer")
		scrollPosition = document.documentElement.scrollTop;
	else
		scrollPosition = window.pageYOffset;		

	if((contentHeight - pageHeight - scrollPosition) < 500){

		if(window.XMLHttpRequest)
			xmlhttp = new XMLHttpRequest();
		else
			if(window.ActiveXObject)
				xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
			else
				alert ("Bummer! Your browser does not support XMLHTTP!");		  

		var url="getImages.php?n="+n;

		xmlhttp.open("GET",url,true);
		xmlhttp.send();

		n += 9;
		xmlhttp.onreadystatechange=putImages;
		contentHeight += 800;
	}
}



Step 20

The final thing that we must do is run the JavaScript at a specified interval.

<body onload="setInterval('scroll();', 250);">

Just set up the "onload" property of the "body" tag, and set its value to the "setInterval" function. This will run the "scroll" function every quarter of a second. Again, you may change this time value, but I found that it’s optimal for what we need.


Finished!

We are done! I hope you found this tutorial to be of help and useful. Please leave a message in the comment section below, should you need further assistance or advice.



Php-fusion Mod 1

Php-fusion Mod 1
I need a Php-Fusion mod, this mod will allow the admin to add a tracking status that will allow users or guests to view how far along their computer repair is.

Back End:
Allow the admin to add a repair to the list: by adding a tracking number, Date/Time Started, Estimated Time till done, Type of computer, Status (Pending, Started, Delayed or Completed) and Date/Time Completed.
Allow the admin to input how the issue was fixed.

Front End:
Users/Members can see all the status by list, or by search tracking number.
Display up to 30 status per page.
Clicking on a tracking number will open a page where the repair can be viewed in detail.

I will need this mod built around the Php-Fusion Infusion, to install.

Any questions, please ask.

Link Click Simulator

Link Click Simulator
I would like web app or program that can simulate clicks on a bit.ly and other URL shortener links.

This application should have an admin backend that allows you to distribute a certain amount of clicks to a specific link or social media account. The clicks should have the option of being distributed over a certain amount of time (3 minutes, 5 minutes and 10 minutes). The clicks would not all be sent evenly.

Scenario:

A twitter account called twitter.com/exampletweeter tweets out a tweet that says:

exampletweeter: This is my great example message http://bit.ly/example

The link above is set to have 100 clicks on it. The clicks will be distributed over 5 minutes. Each minute gets a different percent of clicks.

1st minute gets: 40% of clicks (40 clicks)
2nd minute gets: 25% of clicks (25 clicks)
3rd minute gets: 15% of clicks (15 clicks)
4th minute gets: 10% of clicks (10 clicks)
5th minute gets: 10% of clicks (10 clicks)

A feature / option for adding additional random clicks over the course of a day should be added as well. Random feature check (yes or no) # of random clicks? Enter number. Over the course of 1 hour, 2 hours etc. clicks would be distributed at random intervals.

If possible these clicks should be done through a proxy server to register as different IPs.

The option to either run this click simulator on an entire Twitter account or on a specific link should be an option.

I would prefer this to be in PHP format.

Script Needed Today

Script Needed Today
I need some kind of php script or something that can take product information and input it into each page I need it to go to

I am manually coding content into 1,000 pages; and they have to be done today.
I am coding pages like this: http://essencewebsitedesign.com/usapressuresupply/BE-2600W.html

To pages like this: http://essencewebsitedesign.com/usapressuresupply/BEEX-2505HWX.html

And I need something so I can do this.

Because of the amount of money I have spent on this site, I need something as cheap as possible..

Webform Overlay

Webform Overlay
This page is only in English: https://mozy.com/registration/unlimited

I need a form that creates an overlay in another language. But you may create everything in English and I do the translations myself later.

Your form should have same fields and copy the data to that original page and ‘hit’ continue to the second signup page. Then I need a second overlay page or form to fill in these data.

When this is also filled in it should be copied again to the second original page and then ‘place order’

WordPress Install With Pl ( 3

WordPress Install With Pl ( 3
Hi there – looking for an experienced WP expert to install wordpress for me.

I have the domain purchased and am hosting at Bluehost.

I’d like to have wp installed, the theme i’ll give you the download link to (a free wordpress theme)

You would need to change the permalink structure to

custom – /%category%/%postname%/

I would need the following plugins installed for me:

headspace2
google xml sitemap
wp-stats
sticky
WP-Super-Cache
Twitter Tools (and I would like you to configure that so any new blog posts gets announced on my Twitter id)
Dean’s FCKEditor For WordPress
flash video player
Sociable
vipers video quicktags

And under admin/settings/writing to add the following to the ping list:

http://rpc.pingomatic.com/
http://rpc.shareapost.com/
http://blogsearch.google.com/ping/RPC2
http://api.feedster.com/ping
http://api.moreover.com/ping
http://api.moreover.com/RPC2
http://api.my.yahoo.com/rss/ping
http://bblog.com/ping.php
http://blog.goo.ne.jp/XMLRPC
http://blogdb.jp/xmlrpc/
http://bulkfeeds.net/rpc
http://coreblog.org/ping/
http://ping.bitacoras.com
http://ping.blo.gs/
http://ping.bloggers.jp/rpc/
http://ping.cocolog-nifty.com/xmlrpc
http://ping.fakapster.com/rpc
http://ping.feedburner.com
http://ping.syndic8.com/xmlrpc.php
http://ping.weblogalot.com/rpc.php
http://pinger.blogflux.com/rpc
http://pingoat.com/goat/RPC2
http://rpc.blogrolling.com/pinger/
http://rpc.britblog.com
http://rpc.icerocket.com:10080/
http://rpc.tailrank.com/feedburner/RPC2
http://rpc.technorati.com/rpc/ping
http://rpc.weblogs.com/RPC2
http://rpc.wpkeys.com
http://topicexchange.com/RPC2
http://www.bitacoles.net/ping.php
http://www.blogdigger.com/RPC2
http://www.blogoon.net/ping/
http://www.blogpeople.net/servlet/weblogUpdates
http://xping.pubsub.com/ping

And one last wp install plugin – http://www.bravenewcode.com/products/wptouch/

to allow iphone users to view the site better!

Thanks

Note- this can continue to a long term relationship as i can give you more wp installs if we work together nicely on this one.

Clone Osc Template

Clone Osc Template
Simple project here. I need you to provide a FULLY FUNCTIONAL clone of this OSC Template:

http://www.templatemonster.com/oscommerce-templates/27448.html

Depending on the quality and speed of your work, I might have other work available shortly thereafter. Don’t waste your time with lengthy lists of websites you have developed. I don’t care about that. Also, if you have this entire TM file in your archives already, that would be a plus.

Interactive Website

Interactive Website
A firm or individual is required to the design, development and production of an interactive website aimed at facilitating and improving communication and information sharing amongst both the program staff and departments, current and future collaborators, partner institutions and universities and initiating and enhancing two-way communication between the programme, the scientific and general public. Detailed functions of the site will be discussed with the successful bidders to whom room will be allowed for bid adjustments as per the functions.

Email Monitoring Script

Email Monitoring Script
This project is for an email monitoring script.

What I would like to be able to do is to track the amount of people who either click on my text or image links and those who open the email. I want a database that stores the email addresses of those who click and those who open the mail. This can be achieved through tracking script that is included in the emails and an invisible image that is loaded to track the opens. The emails I send to my subscribers are HTML based emails only.

There would be an admin area that I can log into, to be able to download my clickers file and my openers file. The data should be updated in real-time.

Clone Of Cms Panel .

Clone Of Cms Panel .
Looking for a programmer that is capable of scripting a CMS admin panel for a flash video overlay player that could call up xml and control the position of the player on the web page CSS?
I already have the player done.
Please see this web site.I have found an exact clone of the project that I want you to create. You can see for yourself how user friendly it is and how everything flows. This is what I wanted, exactly. Can you recreate it within 10 days? To take a look go here. http://www.vdolife.com/get_started.php
sign-up for a free account, and see how simple it is to use.
Please do not bid if you are phishing for deposits. This project will be paid by escrow according to a milestone document to be created only.

Taiwan Articles Writer Writing

Taiwan Articles Writer Writing
I need this content completed promptly. The best writer that can complete this project the fastest and the cheapest…gets our business.

I need at least 800-1000 words of content per page with 23 pages

You MUST use my keywords I have within each of my titles in your content. I do not want to have to edit these articles, they must be grammatically correct. These articles must be PROFESSIONALLY written.

Same goes as always¡KI will send your work through CopyScape and will give negative feedback to anyone that¡¦s content is not original. Sorry I have to even say that ƒº

Here are the titles: Content must be written in English

1) Taiwan entertainment & Things to do in Taiwan
2) Places to stay in Taiwan Best Taiwan Hotels
3) Places to visit in Taiwan
4) Best time of year to visit Taiwan
5) Headline news in Taiwan
6) Best Attractions in Taiwan
7) Taiwan to soon make several Apple iPad like devices
8) Non-stop Taipei to London flights launched
9) What kind of food do Taiwanese people like?
10) Taiwan Weather and climates, what is the weather like in Taiwan?
11) Living conditions in Taiwan
12) Taiwan events and celebrations
13) Taiwan airlines and airports
14) Taiwan bullet train high speed rail
15) The best Taiwan Cities to visit
16) The worst Taiwan cities to visit
17) Taiwan currency and Us dollar exchange rate
18) Taiwan holidays and Festivals
19) Taiwan new year
20) What is Taiwan¡¦s population
21) What are the best Taiwan Recipes
22) Taiwan Tourist and Travel guide ideas
23) Best way to learn Taiwan Chinese language Translation

. Total about 18,400 – 23,000 words total.

WordPress Post Sidebar2

WordPress Post Sidebar2
Right now i have a wordpress custom theme,

If they click on a page above they have a custom template sidebar that I choose inside the admin panel..

Example:

I go to wordpress Wp- click add page, i can select what template I want such as

product-sidebar.php

However,

I want inner “POSTS” to have their own sidebars as well so if I create a new post (not a page) and I view it, I want it to have whatever side bar I want it to have such as product, or events.

IF YOU DONT UNDERSTAND THIS DON’T BID, I NEED THIS DONE TODAY, IF YOU CAN’T START RIGHT NOW, DONT BID, IF ITS NOT DONE IN 5-6 HOURS DONT BID.

Flash Work 2

Flash Work 2
Only flash programmers need to bid….We need a flash programmer to assist with our website. Programmer need to know how to do animations and also work with neon colors. Go to youtube.com and look at Tron 2 movie trailer to see neon color ideas we want for our website & www.sportscenter.com , then go to sportscenter remix and view main video screen. We need that type of animation for our logo & plus we need our logo done in colors to match our website. Once the winning bid is selected we will get into more details…..