iScroll has features that make it useful beyond just scrolling – among many uses it can be used to create slide shows. I created one today at work and am sharing the entire process here. I already had certain parts of this done for other parts of my application so it took me about 10 minutes to get everything wired up. Since this example starts from ground zero it will take a little longer.

Start with your layout

This demo will have four slides and we’ll need them in an unordered list, so we will start with this:

<ul>
	<li><img src="images/image_1.jpg" height="177" width="284" /></li>
	<li><img src="images/image_2.jpg" height="177" width="284" /></li>
	<li><img src="images/image_3.jpg" height="177" width="284" /></li>
	<li><img src="images/image_4.jpg" height="177" width="284" /></li>
</ul>

iFramed below is a page with the above code:

Ok, well, thats a start. We’ll be making a horizontal scroller so we need to style this list into a horizontal line using this CSS:

li {
	list-style-type: none;
	margin: 0px;
	padding: 0px;
	float:left;
}
ul {
	width: 1136px;
	margin: 0px;
	padding:0px;
}

A couple things to note:

  • Notice the UL width – since I’m essentially using it as the “wrapper” for the LI elements I need to set the width to equal the total width of all of the slides so that the list items can layout out in the desired manner.
  • I’m floating the list elements instead of setting their display to “inline-block” to be friendlier with old IE

So then, below is the result (scrolling in the iFramed example is on, thus the horizontal scroll bar):

Setup for iScroll

Next we need to setup everything for iScroll which means that we need to create a wrapper around our horizontal thumbnail list and then style it appropriately. Note these three things:

  1. As mentioned I’ve set the width of the UL element so that its width equals the total width of all of the slides since it is the element that will be scrolled ***inside*** of the wrapping div.
  2. The wrapping div has an id of “slideshow” and is styled such that its “viewport” is the same dimensions as a single slide. Note also that it’s overflow is set to “hidden”. If the UL element didn’t have its width set the wrapping div would have forced each slide to stack which is not what we want – we want the slides to lay in a single row.
  3. Within the CSS note the position:relative lines on both the UL and the #slideshow – these are necessary so that iScroll can do the calculations needed to get everything to work. If you forget about this your iScroll wont work at all.
<head>
<style type="text/css">
	li {
		list-style-type: none;
		margin: 0px;
		padding: 0px;
		float:left;
	}
	
	ul {
                position: relative;
		width: 1136px;
		margin: 0px;
		padding:0px;
	}
	
	#slideshow{
		position: relative;
		height: 177px;
		width: 284px;
		overflow: hidden;
	}
</style>

</head>
<body>
	<div id="slideshow">
		<ul>
			<li><img src="images/image_1.jpg" height="177" width="284" /></li>
			<li><img src="images/image_2.jpg" height="177" width="284" /></li>
			<li><img src="images/image_3.jpg" height="177" width="284" /></li>
			<li><img src="images/image_4.jpg" height="177" width="284" /></li>
		</ul>
	</div>
</body>

The following is the result:

Add iScroll

Unlike prior versions iScroll 5 has its own website from which you can download the library at http://iscrolljs.com/. Below is an example of adding it to a page.

<script type="text/javascript" src="js/iscroll.js"></script>

Next we need to initialize the iScroll on our “slideshow” wrapper. We can do so once the page has been loaded like so (jQuery users can substitute jQuery’s document.ready instead). More information on initializing iScroll can be found here.

That’s it – we currently have a functional iScroll – not yet a slideshow, but we’re getting there. Below is the javascript that made it happen followed by the iFramed example.

Of note here is the iScroll configuration object found on line 7. The scrollX property’s “true” value tells iScroll to scroll horizontally.

<script type="text/javascript" src="js/iscroll.js"></script>
<script type="text/javascript">
  ;(function(ns){
	var _iscroll = null;
	ns.init = function(){
		_iscroll = new IScroll('#slideshow',{
			scrollX: true
		});
	}
  })(this.slideshow = {});
  (function(){
	if(window.addEventListener){
		window.addEventListener('load',slideshow.init,false);
	} else{
		window.attachEvent('onload',slideshow.init); //IE
	}
  })();
</script>

Swipe with your finger or your mouse to see the iScroll work.

Configuring iScroll

Ok, now we start getting into the things that will make our slideshow really work. First, lets make iScroll behave a little differently, lets make it snap to each slide instead of scrolling past slides when you swipe. iScroll has 2 properties that we can pass via a configuration object that will tell it to a) snap to an element and b) not overscroll past the element. They are snap and momentum where the former’s value will be set to li since we are snapping to those elements and for the later we’ll use a value of false as we want to disable overswiping.

The adjusted script:

<script type="text/javascript" src="js/iscroll.js"></script>
<script type="text/javascript">
  ;(function(ns){
	var _iscroll = null;
	ns.init = function(){
		_iscroll = new IScroll('#slideshow',{
			scrollX: true
			snap:'li',
			momentum:false
		});
	}
  })(this.slideshow = {});
  (function(){
	if(window.addEventListener){
		window.addEventListener('load',slideshow.init,false);
	} else{
		window.attachEvent('onload',slideshow.init); //IE
	}
  })();
</script>

Give it a try with these new settings:

SPECIAL NOTE: All these examples are iFramed – so if you do a click-drag with a mouse and drag outside of the iFrame then things get kind of weird. This is normal. The explanation is that since you click-dragged outside of the iFrame itself the window within the iFrame does not know that you released the mouse button. Remember: This is a tutorial with “tightly iFramed” examples. To properly experience these examples try to not be so dramatic with your click-swipes 😉

Add next / previous buttons

Slideshows typically have back and next buttons. Lets add them to our slideshow – we’ll start with some basic layout, we’ll have a left and right button on top of the slide show. Each button is a div and will be positioned over the slideshow on the left and right edges.

Here’s the CSS that accomplishes this followed by the HTML:

	#btnleft, #btnright {
		position:absolute;
		top: 70px;
		height: 40px;
		width: 36px;
		z-index: 100;
		background-size:contain;
	}
	#btnleft{
		background-image: url(images/slideshow_left_arrow.png);
		left: 8px;
	}
	#btnright{
		background-image: url(images/slideshow_right_arrow.png);
		left: 255px;;
	}

And the new html – the button divs are added after the slideshow wrapper:

	<div id="slideshow">
		<ul>
			<li><img src="images/image_1.jpg" height="177" width="284" /></li>
			<li><img src="images/image_2.jpg" height="177" width="284" /></li>
			<li><img src="images/image_3.jpg" height="177" width="284" /></li>
			<li><img src="images/image_4.jpg" height="177" width="284" /></li>
		</ul>
	</div>
	<div id="btnleft"></div>
	<div id="btnright"></div>

This is the result:

Add event handlers to the buttons

You should have noticed by now that I’ve made no mention of jQuery thus far and in fact avoided it for the onload event that inits our iScroll. I didn’t want to use jQuery since it would mean using a big fat library to do trivial things. I know everyone likes jQuery so I’ll make a jQuery version that you can download at the end of this article. In the meantime your take-aways should be how to use iScroll not necessarily how to use jQuery for event delegation or whatever. That said, there are more iSrcoll things to learn which we will get to in a moment.

Back on topic, we need to wire up the “back” and “next” buttons. I’ll first wrap everything in a div and then apply the listeners to that wrapping element. The following code does this for us, click the example that follows the code sample to see it work.

The updated init function:

	ns.init = function(){
		_iscroll = new IScroll('#slideshow',{
			scrollX: true,
			snap:'li',
			momentum:false
		});
		// add event listeners
		if (window.addEventListener){
			document.getElementById('slideshow_wrapper').addEventListener('click',ns.doNav,false);
		} else{
			window.attachEvent('onload',slideshow.init); //IE
		}
	};
	ns.doNav = function(e){
		alert('clicked ' + e.target.id);
	};

And the updated HTML with a DIV element with id “slideshow_wrapper” wrapping everything:

	<div id="slideshow_wrapper">
		<div id="slideshow">
			<ul>
				<li><img src="images/image_1.jpg" height="177" width="284" /></li>
				<li><img src="images/image_2.jpg" height="177" width="284" /></li>
				<li><img src="images/image_3.jpg" height="177" width="284" /></li>
				<li><img src="images/image_4.jpg" height="177" width="284" /></li>
			</ul>
		</div>
		<div id="btnleft"></div>
		<div id="btnright"></div>
	</div>

Click the arrows….

What I’ve done is set things to capture the click events as they bubble up the DOM to the event listeners (a technique referred to as event delegation).

Add logic to the navigation buttons

Our buttons will advance the slideshow either forward or backward. To do this we need to be able to determine the direction the user wants to go. If you clicked the navigation buttons in the above example you can see that the alert contained the id of the clicked element, so I’ll use that to determine which button was clicked. Below is the modified doNav function that keys in on the id’s of our buttons:

    ns.doNav = function(e){
	if (e.target.id === 'btnleft'){
	    // move the sideshow to the left
	} else {
	    // move the slideshow to the right
	}
    };

The next thing we need is a way of advancing the slideshow in one direction or another. iScroll provides a method for this purpose called next() to advance the slideshow forward and prev() to advance the slideshow to a previous slide. There is also goToPage() but I’ll stick with the previous two methods – you can of course opt to use the later method to take advantage of the easing property that it exposes.

This is all we need to get the navigation buttons working. See the code below followed by the working example.

    ns.doNav = function(e){
	if (e.target.id === 'btnleft'){
	    iscroll.prev(); // scroll left
	} else {
	    iscroll.next(); // scroll right
	}
    };

Dimming the navigation buttons

One thing that you might think is missing is disabling the buttons in some way to reflect that you are either at the beginning or end of the slideshow. By digging into the iScroll object we can find some properties that will make it easy for us to do this.

First we will need to know what the current slide number is. That information is held in the iScroll object that can be referenced via our private _iscroll variable. Log your iScroll object to the console and note the currentPage property. Expand it and you will see the following:

currentPage:{
    pageX:0, // this holds the slide number for horizontal iScrolls
    pageY:0, // this holds the slide number for vertical iScrolls
    x:-0,
    y:0
}

As you can see the pageX property holds the slide number for horizontal scrollers. Given that fact we would access the current slide number by doing this:

var slideNumber = _iscroll.currentPage.pageX;

Next we need to know how many slides there are. Of course we know that there are 4 but iScroll also holds this for us in the iScroll object’s pages property. Lets save it for later use:

var slideLength = _iscroll.pages.length;

Below is a function that dims the navigation buttons when they are no longer usable due to the slideshow being either at the beginning or end of the slide list (if you are using jQuery you will want to add or remove css classes to the elements instead of the in-line editing that I’m doing):

    // show or dim the navigation buttons
    function _hideShowNavButtons(e){
	var slideNumber = _iscroll.currentPage.pageX;
	var slideLength = _iscroll.pages.length - 1;
	// show or hide the next and previous buttons according to where we are in the slideshow
	document.getElementById('btnleft').style.opacity = slideNumber === 0 ? .3 : 1;
	document.getElementById('btnright').style.opacity = slideNumber === slideLength ? .3 : 1;
    }

To make the above work we need to fire it when the slideshow has stopped scrolling – thus we’ll hook into iScroll’s scrollEnd event. We’ll do this within the init() function which has been modified below:

    // init the app
    ns.init = function(){
	_iscroll = new IScroll('#slideshow',{
	    scrollX: true,
	    snap:'li',
	    momentum:false
	});
		
	// add scrollend event to iscroll
	_iscroll.on('scrollEnd',_hideShowNavButtons); // NEW LINE!! dim or show the buttons on "scrollEnd"
		
	// add event listeners
	if (window.addEventListener){
	    document.getElementById('slideshow_wrapper').addEventListener('click',ns.doNav,false);
	} else {
	    window.attachEvent('onload',slideshow.init); //IE
	}
    };

Lastly, we need to code the “Previous” button so that it is dimmed to begin with. I hardcode that into the init() function via this line (as before use jQuery or your favorite library instead as needed):

// set the default state for the left/previous button
document.getElementById('btnleft').style.opacity = .3;

Here is the result:

We’re done! You could of course add a lot more features such as notes or slide numbering, etc. Right-click and inspect the iFrame holding the final example above or see the complete source printed out below.

<!DOCTYPE html>
<html><head><title></title>

<style type="text/css">
    li {
	list-style-type: none;
	margin: 0px;
	padding: 0px;
	float:left;
    }
	
    ul {
	position: relative;
	height: 177px;
	width: 1136px;
	margin: 0px;
	padding:0px;
    }
	
    #slideshow{
	position: relative;
	height: 177px;
	width: 284px;
	overflow: hidden;
    }
    #btnleft, #btnright {
	position:absolute;
	top: 70px;
	height: 40px;
	width: 36px;
	z-index: 100;
	background-size:contain;
    }
    #btnleft{
	background-image: url(images/slideshow_left_arrow.png);
	left: 8px;
    }
    #btnright{
	background-image: url(images/slideshow_right_arrow.png);
	left: 255px;
    }
</style>

<script type="text/javascript" src="js/iscroll.js"></script>
<script type="text/javascript">
;(function(ns){
    // hold a reference to the iScroll object
    var _iscroll = null;
	
    // init the app
    ns.init = function(){
	_iscroll = new IScroll('#slideshow',{
	    scrollX: true,
	    snap:'li',
	    momentum:false
        });
		
        // add scrollend event to iscroll
        _iscroll.on('scrollEnd',_hideShowNavButtons);
		
	// set the default state for the left/previous button
	document.getElementById('btnleft').style.opacity = .3;
		
	// add event listeners
	if (window.addEventListener){
	    document.getElementById('slideshow_wrapper').addEventListener('click',ns.doNav,false);
	} else {
	    window.attachEvent('onload',slideshow.init); //IE
	}
    };
	
    // handle navigation button clicks
    ns.doNav = function(e){
	if (e.target.id === 'btnleft'){
	    _iscroll.prev(); // scroll left
	} else {
	    _iscroll.next(); // scroll right
	}
    };
	
    // show or hide the navigation buttons
    function _hideShowNavButtons(e){
	var slideNumber = _iscroll.currentPage.pageX;
	var slideLength = _iscroll.pages.length - 1;
	// show or hide the next and previous buttons according to where we are in the slideshow
	document.getElementById('btnleft').style.opacity = slideNumber === 0 ? .3 : 1;
	document.getElementById('btnright').style.opacity = slideNumber === slideLength ? .3 : 1;
    }
	
})(this.slideshow = {});

;(function(){
    if (window.addEventListener){
	window.addEventListener('load',slideshow.init,false);
    } else {
	window.attachEvent('onload',slideshow.init); //IE
    }
})();
</script>
</head>
<body>
    <div id="slideshow_wrapper">
	<div id="slideshow">
	    <ul>
		<li><img src="images/image_1.jpg" height="177" width="284" /></li>
		<li><img src="images/image_2.jpg" height="177" width="284" /></li>
		<li><img src="images/image_3.jpg" height="177" width="284" /></li>
		<li><img src="images/image_4.jpg" height="177" width="284" /></li>
	    </ul>
	</div>
	<div id="btnleft"></div>
	<div id="btnright"></div>
    </div>
</body>
</html>