Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Replicating the Swipe Gesture iPhone Gallery for mobile web– HTML5 – Part 2


Published on

In this tutorial we will talk about building up a Swipe Gesture photo gallery for iPhone, iPod using web technologies – HTML5, CSS3 and JavaScript. To begin with, you might have viewed pictures in your iPhone or iPod photo library and may remember how you used to swipe your finger across the screen of your device to view the next or the previous image in the gallery. The same thing we are going to replicate and make a mobile web app. Our app will run full screen on the mobile safari browser so this gives it a native look n feel.

Published in: Technology, Design
  • Be the first to comment

  • Be the first to like this

Replicating the Swipe Gesture iPhone Gallery for mobile web– HTML5 – Part 2

  1. 1. Replicating the Swipe Gesture iPhone Gallery for mobile web– HTML5– Part 2 Interaction – The JavaScript codeBy looking at the java script code you might have a question in your mind that this time I have used a different way ofwriting my javascript code. What I have done is that I have created a self calling function and I have defined an object(swipey) inside the function and finally exposed the object to the window object (window.swipeyObj = swipey) sothat I can call the properties and methods of the swipey object anywhere after including the javascript file to ourlibrary. Ofcourse there are several other ways to execute the same, but this way it maintains the scope of theproperties and methods of the object.Let’s go straight to the swipey object which follows a JSON pattern. Inside the swipey object we have defined aseries of properties and the methods. Think of it as a Class, but there are slight differences between a JSON Objectand a Class. We will not go into that at the moment. The basic structure of swipey object is shown below,var swipey = { property1:value1, property2:value2, …………… method1:function(){}, method2:function(){}, ……………};To access a property we write swipey.property1 and to call a method swipey.method1(). Ok, that’s quite a briefdescription of a JSON object. Also, at most places I have provided comments for understanding. Now,theinitSwipey() method defines some basic operations which is simple enough to understand. window.scrollTo(0,1);is for hiding the address bar of the browser to give the app a native look. I have already talked about it in details inmy earlier post, here. One thing to be noticed is the line below, = swipey.slides.length * swipey.preferredWidth +"px";If you remember we should have our slides (<li>) horizontally placed and for that we have set float:left in CSS. Butthat is not enough for them to be placed horizontally inside the container (<ul>) element. We also need to provideenough space to the container so that all the slides are arranged horizontally and for that we have to set the width ofthe container towidth_of_container = number_of_slides * width_of_one_slide;We could have hardcoded the value of width in CSS, but to keep things dynamic I have done it in script block. Now,it doesnot matter how many slides you add, you do not have to calculate the width value manually and change it inCSS. The script will do it for you. Finally, the last line of initSwipey() makes a call to initEvents().
  2. 2. Inside initEvents() function all the event listeners are registered. This is a touch based app so we have touchevents. Note that I have added the event listeners to the wrapper. You can add it to the container <ul> element also. Ifelt it better to add to the wrapper.Next up, for each touch based event I have defined listener functions which will handle the actions when thecorresponding event is fired.startHandler function()This function is called when touch start event is fired. Inside it we mainly store the starting X co-ordinate of the touchpoint and save it in swipey.startX. Also we set our timer on.moveHandler function()This function is called when the figer moves over the device screen. It is called repeatedly each time the finger ismoved. Here we calculate the net distance that the container should move relative to the start pointswipey.distanceX = event.touches[0].pageX - swipey.startX;and then we translate the container <ul> element by that much distance. Now which direction – left or right dependson the value of distanceX, if it is negative it moves to the left and if positive moves to the = "translate3d(" + (swipey.distanceX +swipey.currentDistance) + "px, 0,0)";Also we have a value of currentDistance added to the distanceX. This is because when we translate the <ul> elementthe co-ordinate system moves by that distance. So next time whenever it is moved again the earlier position shouldbe taken into consideration.endHandler function()And then we have our endHandler() function which is called when the finger leaves the screen. Here the finalmovement is made based on the direction. We check the following conditions here,1) The direction of movement – left or rightif (swipey.distanceX > 0) { swipey.direction = "right";}if (swipey.distanceX < 0) { swipey.direction = "left";}2) If it is the beginning of the gallery and you are swiping to the right then the images will come back / If itis the end of the gallery and you are swiping to the left then the images will come back. (Feature no. 4 fromthe list that I discussed in Part1)
  3. 3. if ((swipey.direction == "right" && swipey.currentDistance == 0) || (swipey.direction== "left" && swipey.currentDistance == -(swipey.maxDistance - swipey.preferredWidth))){ swipey.comeBack();}3) If the swiping is very fast and instantly you flicker the images with minimum distance swiped is 10 forright direction and -10 for left, then the previous slide or the next slide is displayed respectively. (Feature no.2 from the list that I discussed in Part1)else if (swipey.timerCounter < 30 && swipey.distanceX > 10) { swipey.moveRight();}else if (swipey.timerCounter < 30 && swipey.distanceX < -10) { swipey.moveLeft();}4) If you swipe the current image a minimum distance of half the screen width then the next or previousimage is displayed based on the direction of swipe. (Feature no. 1 from the list that I discussed in Part1)else if (swipey.distanceX <= -(swipey.preferredWidth / 2)) //-320/2 swipey.moveLeft();}else if (swipey.distanceX >= (swipey.preferredWidth / 2)) //320/2 swipey.moveRight();}5) If any of the conditions are not met then the image will come back to its original position. (Feature no. 3from the list that I discussed in Part1)else { swipey.comeBack();}
  4. 4. Next, there are specific methods for translating/moving the slide container to left or right and also come back tocurrent position.moveLeft: function() { swipey.currentDistance += -swipey.preferredWidth; = 300 + "ms"; //using CSS3 transformations - translate3d function for movement = "translate3d(" +swipey.currentDistance + "px, 0,0)";},moveRight: function() { swipey.currentDistance += swipey.preferredWidth; = 300 + "ms"; = "translate3d(" +swipey.currentDistance + "px, 0,0)";},comeBack: function() { = 250 + "ms"; = "ease-out"; = "translate3d(" +swipey.currentDistance + "px, 0,0)";}moveLeft() and moveRight() are very similar, only the calculation of swipey.currentDistance variable isdifferent.Note that we have to translate the <ul> slide container by 320px(preferredWidth) left or right everytime forthe neighboring slides to be visible. And finally we expose the swipey object to the global window object.window.swipeyObj = swipey;Finally we have the full java script code below with inline comments,(function() {
  5. 5. var swipey = {slideContainer: null, //<ul> element object that holds the image slideswrapper: null, //meant for masking/clippingslides: null, //array of all slides i.e <li> elementsdistanceX: 0, //distance moved in X direction i.e left or rightstartX: 0, //registers the initial touch co-ordinatepreferredWidth: 0, //dynamic variable to set widthpreferredHeight: 0, //dynamic variable to set heightdirection: "", //direction of movementtimer: null, //timer that set starts when touch startstimerCounter: 0, //counter variable for timerisTouchStart: false, //boolen to chk whether touch has startedmaxDistance: 0, //maximum distance in X direction that slide container can movecurrentDistance: 0, //current distance moved by slide container through translateinitSwipey: function() {//scroll the window up to hide the address bar of the browser.window.setTimeout(function() { window.scrollTo(0, 1); }, 100);//get all the instances of the HTML elementsswipey.wrapper = document.getElementById("wrapper");swipey.slideContainer = document.getElementById("slideContainer");swipey.slides = slideContainer.getElementsByTagName("li");//for iPhone, the width and height
  6. 6. swipey.preferredWidth = 320;swipey.preferredHeight = 416; //510 for android//setting the width and height to our wrapper with overflow = = swipey.preferredWidth + "px"; = swipey.preferredHeight + "px";//setting the width to our <ul> element which holds all the <li> = swipey.slides.length * swipey.preferredWidth +"px"; = swipey.preferredHeight + "px";//calculating the max distance of travel for Slide Container i.e <ul> elementswipey.maxDistance = swipey.slides.length * swipey.preferredWidth;//initialize and assign the touch eventsswipey.initEvents();},initEvents: function() {//registering touch events to the wrapperswipey.wrapper.addEventListener("touchstart", swipey.startHandler, false);swipey.wrapper.addEventListener("touchmove", swipey.moveHandler, false);swipey.wrapper.addEventListener("touchend", swipey.endHandler, false);},//funciton called when touch start event is fired i.e finger is pressed on the screenstartHandler: function(event) {//stores the starting X co-ordinate when finger touches the device screenswipey.startX = event.touches[0].pageX; //.changedTouches[0]//timer is set on
  7. 7. swipey.timer = setInterval(function() { swipey.timerCounter++; }, 10);swipey.isTouchStart = true;event.preventDefault(); //prevents the window from scrolling.},//funciton called when touch move event is fired i.e finger is dragged over the screenmoveHandler: function(event) {if (swipey.isTouchStart) {swipey.distanceX = event.touches[0].pageX - swipey.startX;//move the slide container along with the movement of the = "translate3d(" + (swipey.distanceX +swipey.currentDistance) + "px, 0,0)";}},//funciton called when touch end event is fired i.e finger is released from screenendHandler: function(event) {clearInterval(swipey.timer); //timer is stoppedif (swipey.distanceX > 0) {swipey.direction = "right";}if (swipey.distanceX < 0) {swipey.direction = "left";}//the following conditions have been discussed in detailsif ((swipey.direction == "right" && swipey.currentDistance == 0) || (swipey.direction== "left" && swipey.currentDistance == -(swipey.maxDistance - swipey.preferredWidth))){
  8. 8. swipey.comeBack();}else if (swipey.timerCounter < 30 && swipey.distanceX > 10) {swipey.moveRight();}else if (swipey.timerCounter < 30 && swipey.distanceX < -10) {swipey.moveLeft();}else if (swipey.distanceX <= -(swipey.preferredWidth / 2)) { //-160swipey.moveLeft();}else if (swipey.distanceX >= (swipey.preferredWidth / 2)) { //160swipey.moveRight();}else {swipey.comeBack();}swipey.timerCounter = 0; //reset timerCounterswipey.isTouchStart = false; //reset the boolean varswipey.distanceX = 0; //reset the distance moved for next iteration},moveLeft: function() {swipey.currentDistance += -swipey.preferredWidth;
  9. 9. = 300 + "ms";//using CSS3 transformations - translate3d function for = "translate3d(" + swipey.currentDistance+ "px, 0,0)";},moveRight: function() {swipey.currentDistance += swipey.preferredWidth; = 300 + "ms"; = "translate3d(" + swipey.currentDistance+ "px, 0,0)";},comeBack: function() { = 250 + "ms"; = "ease-out"; = "translate3d(" + swipey.currentDistance+ "px, 0,0)";}}; //end of swipey objectwindow.swipeyObj = swipey; //expose to global window object})();swipeyObj.initSwipey(); //invoke the init method to get startedThe code can be modified and manipulated as per your need. The same logic however, can be used to build theiPhone/Android carousel menu as well. And here it is, the link for the demo app for mobiledevice: it in your iPhone or Android smartphone browser and swipe across the screen. For a desktop browser version(Chrome and Safari – webkit browsers only) here is the link: completes our two part series of Swipe Gesture gallery. Hope you find it useful.