Mobile Menu Icon
Your Web Pro Logo

A Super Simple Image Slider

Kaiser Keenmon — 2016-05-27

I've always used – open source – third party image sliders when building websites because they're easy to implement, provide an abundance of options and features, and function quite well. And while there are some good all purpose sliders out there, no slider is perfect. So it makes sense to have a familiarity with several different sliders that you can then just pick and choose from based on your project requirements. In fact, I've been toying around with a few different ones lately searching to find one or two that either integrate and/or function better somehow. Interestingly, one of our latest projects is a website that calls for a super simple image slider. And while I know of a few nice sliders I could use for this, I don't know of any that are both simple to customize and not bloated with markup, styles and code. So for this project I opted to build one!

Getting started, I thought it would be nice to have the slider automatically populated with any images uploaded to the slider images folder to make it extremely easy to update. That way, any images that get added to the slider images folder will be automatically displayed by the slider without having to update the code as well. Here's what I put together for that:

<div id="slider">
<?php
$i = 0;
$dir = 'images/slider/';
// open directory and grab its contents.
// $handle = reference to directory resource.
if ($handle = opendir($dir)) {
//returns the name of the next entry in the directory. returns false on failure
while (($file = readdir($handle)) !== false){
// if not a directory
if (!is_dir($dir.$file)) {
?>
<img id="slide-<?php echo $i; ?>" src="images/slider/<?php echo $file ?>" alt="Slide-<?php echo $i; ?>" />
<?php
$i++;
}
}
} ?>
</div><!-- END #slider –>

So, this code is essentially a div element '<div id="slider"></div><!-- END #slider –>' to house the images which are being output through the img tag '<img id="slide-<?php echo $i; ?>" src="images/slider/<?php echo $file ?>" alt="Slide-<?php echo $i; ?>" />'. And as you can see, I set counter variable $i to 0, and variable $dir to the path of my slider images directory, 'images/slider/'. I then open the images directory with the function 'opendir($dir)', grab its contents in the form of a directory handle and store it in the variable '$handle'. If the directory handle is successfully opened I then loop through its contents with a while loop. Next, I test each entry in the handle. If the entry is not itself a directory, but a file, I output it with the img tag.

You can see, that on each iteration of the loop, the next entry in the handle is stored in the variable '$file'. I use this variable in the img tag to set the img tag's src attribute. In addition, I set the id of the img tag with the contents of variable '$i', which gets incremented by a value of 1 each iteration of the loop. I'll use this id – which again, is generated on each iteration of the loop – to reference the images with jQuery, which I'll be using to 'slide' the images.

Now, if I were to load some images into the slider images folder and then display the slider in a browser, we'd see all of the images output on to the page one right after the other. So to reiterate, each of the images would be output to the page one by one each iteration of the while loop.

So far so good, but we don't want to display all of the images at the same time, so next, I'll add some css styles to set the dimensions of the slider elements. Here's the css:

body {
padding-top:100px;
}
#slider {
height:500px;
overflow:hidden;
width:950px;
margin:0 auto;
}
#slider img {
width:100%;
height:auto;
opacity:0;
}
#slider img:nth-of-type(1) {
opacity:1;
}

First, I add some padding to the top of the body element to push the slider down a bit so it's not flush with the top of the page. Then I give the slider div a height of 500px and set its overflow property to 'hidden'. I'll explain.

So in order make the slider images display more consistently I could (and should) resize each of the images to have a height equal to that of the slider div (in this case 500px) before uploading them to the slider images directory. That way the entire height of the images will be displayed by the slider within the 500px height of the slider. But let's say that I don't do this and I instead upload an image with a height of 800px. What will happen is that yes, the entire image will be displayed, but with a height of 800px that will overflow the bounds of the slider div. So to completely prevent overflow from happening, I set the slider divs overflow property to 'hidden'. This will effectively cut off the bottom of any image that has a height greater that 500px. So for the 800px image in the example above, the bottom 300px would be cut off.

That could be a problem depending on the image. We definitely don't want to cut off key elements of an image, so some images may need to be resized to get them to display properly, but for other images it may fine. The overflow property may only cut off non-essential portions of an image. In those cases having the overflow property set to hidden can actually save us the time and effort required to first resize the images prior to upload.

So moving on, I next set the slider divs width to '950px' and its margin to '0 auto'. This is just to give my slider the width needed for my project and to center it horizontally on the page.

I then set the dimensions of each image to a width of '100%' and a height of 'auto'. Doing this will cause each image to fill the entire width of the slider div. And, by setting the height property to 'auto', if I were to later change the slider divs width from '950px' to a percentage width like let's say, '100%' (which would cause the slider to span the width of the page), then the height of each image would automatically adjust along with the image width preserving the images aspect ratio at different browser viewport widths. Essentially this will allow me to make the slider mobile responsive if required.

Moving on, you'll see that I set the opacity property of each image to 0. I then change the opacity property of just the very first image to 1. This way, when the page initially loads, the first image will be visible and all other images won't be. This will allow me to then smoothly fade each image in one after another.

So with our styling complete, if we were to now load the slider in a browser, we'd see the top of our slider 100px from the top of the page. It would have a width of 950px, a height of 500px, and it would be horizontally centered on the page. We'd also see only the first of the slider images. Next we'll make the images 'slide'.

Here's the jQuery:

$(window).load(function() {
var slider = $("#slider");
var images = $('img', slider);
var settings = {
slideDuration: 8000,
fadeOutSpeed: 400,
fadeInSpeed: 1500
}
var i = 0;
setInterval(function () {
var i2 = i + 1;
if (i >= (images.length)) {
i = 0;
i2 = i + 1;
}
$("#slide-" + i).animate({opacity: 0}, settings["fadeOutSpeed"], function () {
if(i2 >= images.length) {
$("#slide-" + i).css("display", "none");
$("#slide-" + 0).animate({opacity: 1}, settings["fadeInSpeed"]);
$(images).each(function() {
$(this).css("display", "block");
});
i++;
} else {
$("#slide-" + i).css("display", "none");
$("#slide-" + i2).animate({opacity: 1}, settings["fadeInSpeed"]);
i++;
}
});
}, settings["slideDuration"]);
});

Wrapping everything inside the '$(window).load()', function ensures that everything, including the entire DOM and all of the requested images, are fully loaded and accessible before trying to act on them. This will prevent the code from trying to act on elements that've yet to load.

Next, I initialize some variables with the slider elements for ease of access. I set variable 'slider' with an object representation of the slider div, and set the 'images' variable with an array of object representations of each img element.

I then create the variable 'settings' and assign to it an object with members 'slideDuration', 'fadeOutSpeed', and 'fadeInSpeed'. I'll use these to set the duration that each slide will appear and also the fade in and fade out transition speeds of each slide.

Next I set up another loop (or at least what functions like a loop), but while the php loop outlined above is used to grab the images and output them to the browser, this loop is used to 'slide' the images in and out one by one at a desired interval.

To do this, I first set up counter variable 'i' and initialize it to 0 (essentially I use this variable to reference the current image being displayed by the slider, this is how the code 'knows' which image to slide out next). I then use the native javascript function, setInterval() and pass in an anonymous self-executing function that comprises the code that will execute each interval or iteration of the 'loop'.

Within the setInterval() function, I set up another variable 'i2' (essentially I use this variable to reference the next image that will be displayed by the slider. This is how the code 'knows' which image to display next), and iniatialize it to the value of variable 'i + 1'. Notice the statements 'i++', within the 'if else' statement. One of these will execute on each iteration of setInterval() and will increment the value in variable 'i' by a value of one each time. Incrementing 'i' on each iteration of the setInterval() function will allow us to act on each subsequent image one by one. The first 'if' statement in setInterval() compares the value stored in variable 'i' against the number of images in the array of images, 'images' initialized above. If variable 'i' is greater than the number of image objects, then 'i' is set to the value of '0', and 'i2' is then set to the value of 'i + 1' again (which would now equal '1'). This will cause the setInterval() function to start again at the very first image in the array each time it reaches the end of the image array.

To make the images actually 'slide' in and out (or fade in and out really), I use the jQuery animate() function. On each iteration of setInterval(), I say, '$("#slide-" + i).animate({opacity: 0}, settings["fadeOutSpeed"], function () {

On each iteration, this statement animates the next image in the image array and changes its degree of opacity from 100% opaque to completely transparent over the specified time span, 'settings[“fadeOutSpeed”]' – which I've set to 400 milliseconds in the 'settings' object outlined above. This will cause the current image being displayed by the slider to fade out at the specified speed – after being displayed for the specified duration 'settings[“slideDuration”]'.

Now for the tricky part. The third argument passed to animate() is a callback functions that executes each time right after the 'fade out' animation completes. Within this callback function is an 'if else' statement. The 'if' statement – which will run one iteration before the first 'if' statement above – takes the value stored in 'i2' and compares it against the number of images in the array of images 'images' initialized above. If at this point the slider is currently displaying the last image in the array of images, then the next image would be the first image in the image array. So here I use the statement '$("#slide-" + 0).animate({opacity: 1}, settings["fadeInSpeed"]);' to fade in the first image in the array. Keep in mind that on the very next iteration of setInterval() that the first if statement will now test true and execute the code outlined above causing the slider to essentially start again at the very beginning of image array.

Next, I use the 'each()' function to set each images display property to 'block' again so that when we begin looping through them again they'll be visible. This is necessary, because as you'll notice, after I slide each image out, I set its display property to 'none', which essentially removes the image from the page layout and frees up the space that it would have otherwise occupied. Doing this allows the next image that slides in to shift higher up on the the page, effectively filling in the space the previous image occupied. We just have to reset the display property back to block for each of the images so that we can then display them again one by one.

Within the 'else' block is code that executes for each and every slide. The 'if' statement above just basically resets the slider when setInterval() reaches the end of the image array. But the 'else' statement slides each image in exept for the first image which is already set to display on page load, or is displayed in the second 'if' statement outlined above. Within the 'else' block I set the image that just faded out to 'display:none', and then slide the next image in.

You'll notice that the last statement in both the 'if' and 'else' blocks is 'i++'. This keeps the slider iterating over each subsequent image in the array.

Finally, you'll see that the second and last argument passed to the setInterval() function is 'settings[“slideDuration”]'. In this example, this tells setInterval() to iterate every 8000 milliseconds, or 8 seconds.

And there you have it, a super simple image slider! Very few lines of code, simple to style, configure and implement, and easy to update.




Your Name:
Your Company
Your Phone Number:
Your Email Address:
Your Mailing Address:
City:
State:
Zip:
Comments and Notes:
Join Our E-Mail List:



How Did You Hear About Us?