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

 1 2   3   4 
 5   6   7   8   9   10   11   12   13   14   15 

9 Images Displayed | top

 16 
 17 
 18  

## Step 3: CSS

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

 1 2 body{  3  background:#222;  4  color:#666;  5 }  6 #header{  7  font-family:Arial, Helvetica, sans-serif;  8  font-size:24px;  9  font-weight:bold;  10  text-align:left;  11  text-indent:35px;  12  margin: 0 auto;  13  width:800px;  14  margin-bottom:10px;  15 }  16 hr{  17  margin: 20px;  18  border:none;  19  border-top: 1px solid #111;  20  border-bottom: 1px solid #333;  21 }  22 p{  23  color:#444;  24  text-align:left;  25  font-size:10px;  26  margin-left: 20px;  27  margin-bottom: -10px;  28 }  29 a{  30  color:#444;  31 } 

## Step 4

 1 2 #container{  3  margin: 0 auto;  4  width:800px;  5  border:1px solid #333;  6  -moz-border-radius: 10px;  7  -webkit-border-radius: 10px;  8  font-family:Verdana, Geneva, sans-serif;  9  text-align:center;  10 }  11 img{  12  border:10px solid #444;  13  -moz-border-radius: 5px;  14  -webkit-border-radius: 10px;  15  margin: 15px;  16 }  17 img:hover{  18  border-color:#555;  19  -moz-box-shadow: 0px 0px 15px #111;  20  -webkit-box-shadow: 0px 0px 15px #111;  21 } 

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

 1 2 

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.

 1 2 $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.

 1 2  $n =$_GET["n"];  3  $response = "";  We get the URL parameter for the index of the next image we need, and we initialize our response text.  1   2  for($i = $n;$i<$n+9;$i++)  3  $response =$response.$files[$i%count($files)].';';  4  echo$response;  5 }  6 ?> 

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.

 1 2  $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.

 1 2  

## Step 8: JavaScript

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

 1 2 var contentHeight = 800;  3 var pageHeight = document.documentElement.clientHeight;  4 var scrollPosition;  5 var n = 10;  6 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.

 1 2 function putImages(){  3  if (xmlhttp.readyState==4){  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;

 1 2 var resp = xmlhttp.responseText.replace("\r\n", "");  3 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.

 1 2  var j = 0;  3  for(i=0; i';  6  j++;  7   8  if(j == 3 || j == 6)  9  document.getElementById("container").innerHTML += '';  10  else if(j == 9){  11  document.getElementById("container").innerHTML += '

'+(n-1)+" Images Displayed | top

";  12  j = 0;  13  }  14  }  15  } 

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.

 1 2 function putImages(){  3  if (xmlhttp.readyState==4){  4  if(xmlhttp.responseText){  5  var resp = xmlhttp.responseText.replace("\r\n", "");  6  var files = resp.split(";");  7   8  var j = 0;  9  for(i=0; i';  12   13  j++;  14  if(j == 3 || j == 6)  15  document.getElementById("container").innerHTML += '';  16  else if(j == 9){  17  document.getElementById("container").innerHTML += '

'+(n-1)+" Images Displayed | top

";  18  j = 0;  19  }  20  }  21  }  22  }  23  }  24 } 

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

 1 2 function scroll(){  3   4  if(navigator.appName == "Microsoft Internet Explorer")  5  scrollPosition = document.documentElement.scrollTop;  6  else  7  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

 1 2  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.

 1 2  if(window.XMLHttpRequest)  3  //Firefox, Opera, Safari  4  xmlhttp = new XMLHttpRequest();  5  else  6  if(window.ActiveXObject)  7  //Internet Explorer  8  xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");  9  else  10  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.

 1 2  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.

 1 2  xmlhttp.open("GET",url,true);  3  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.

 1 2  n += 9;  3  contentHeight += 800;  4  xmlhttp.onreadystatechange = putImages;  5  }  6 } 

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.

 1 2  

## Step 20

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

 1 2  `

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.