Articles

Jquery Slider for Iphone and Android with Jquery Cycle and Swipe Plugins


I always use jQuery cycle plugin whenever I need a slider.jQuery Cycle plugin is very much handy and gives a lot of option to play with. While I was working with a mobile website, it required an image slider with iPhone and Android swipe effect. Since I already used to jquery cycle for the slider, it was difficult for me to try a new slider plugin and also most of them have not satisfied my all requirement. So I tried to tweak the code to handle the swipe effect along with jQuery Cycle.

For this we need three plugins jQuery cycle, jquery easing and jQuery Swipe. But I made a small tweak in the jquery swipe plugin to work fine with the slider. Find the below code along with the tweak.

Step 1: Add the below swipe plugin and jquery cycle to your web page.

/*
 * jSwipe - jQuery Plugin
 * http://plugins.jquery.com/project/swipe
 * http://www.ryanscherf.com/demos/swipe/
 *
 * Copyright (c) 2009 Ryan Scherf (www.ryanscherf.com)
 * Licensed under the MIT license
 *
 * $Date: 2009-07-14 (Tue, 14 Jul 2009) $
 * $version: 0.1.2
 *
 * This jQuery plugin will only run on devices running Mobile Safari
 * on iPhone or iPod Touch devices running iPhone OS 2.0 or later.
 * http://developer.apple.com/iphone/library/documentation/AppleApplications/Reference/SafariWebContent/HandlingEvents/HandlingEvents.html#//apple_ref/doc/uid/TP40006511-SW5
 */
(function($) {
	$.fn.swipe = function(options) {
 
		// Default thresholds & swipe functions
		var defaults = {
			threshold: {
				x: 10,
				y: 30
			},
			swipeLeft: function() {alert('swiped left')},
			swipeRight: function() {alert('swiped right')},
                        swipeMoving: function( value ){alert( value )}
		};
 
		var options = $.extend(defaults, options);
 
		if (!this) return false;
 
		return this.each(function() {
 
			var me = $(this)
 
			// Private variables for each element
			var originalCoord = {x: 0, y: 0}
			var finalCoord = {x: 0, y: 0}
 
			// Screen touched, store the original coordinate
			function touchStart(event) {
				//console.log('Starting swipe gesture...')
				originalCoord.x = event.targetTouches[0].pageX
				originalCoord.y = event.targetTouches[0].pageY
			}
 
			// Store coordinates as finger is swiping
			function touchMove(event) {
 
                                if(event.touches.length > 1 || event.scale && event.scale !== 1){
                                    return;
                                }
 
				finalCoord.x = event.targetTouches[0].pageX; // Updated X,Y coordinates
				finalCoord.y = event.targetTouches[0].pageY;
                                changeX = originalCoord.x - finalCoord.x;
                                changeY = originalCoord.y - finalCoord.y;
 
                                if ( typeof this.isScrolling == 'undefined') {
 
                                 this.isScrolling = !!( this.isScrolling || Math.abs(changeX) < Math.abs(changeY) );                                 }                                if( !this.isScrolling )                                { 				   // console.log(changeX);                                    event.preventDefault();                                    defaults.swipeMoving( changeX ); 			       } 			} 			// Done Swiping 			// Swipe should only be on X axis, ignore if swipe on Y axis 			// Calculate if the swipe was left or right 			function touchEnd(event) { 				//console.log('Ending swipe gesture...') 				var changeY = originalCoord.y - finalCoord.y;                            if (!this.isScrolling) { 					changeX = originalCoord.x - finalCoord.x 					if(changeX > defaults.threshold.x) {
 
                                           defaults.swipeLeft()
					}
					if(changeX < (defaults.threshold.x*-1)) {
                                            defaults.swipeRight()
					}
				}
			}
 
			// Swipe was started
			function touchStart(event) {
				//console.log('Starting swipe gesture...')
 
                                this.isScrolling = undefined;
				originalCoord.x = event.targetTouches[0].pageX
				originalCoord.y = event.targetTouches[0].pageY
 
				finalCoord.x = originalCoord.x
				finalCoord.y = originalCoord.y
			}
 
			// Swipe was canceled
			function touchCancel(event) {
				//console.log('Canceling swipe gesture...')
 
			}
 
			// Add gestures to all swipable areas
			this.addEventListener("touchstart", touchStart, false);
			this.addEventListener("touchmove", touchMove, false);
			this.addEventListener("touchend", touchEnd, false);
			this.addEventListener("touchcancel", touchCancel, false);
 
		});
	};
})(jQuery);

Step 2: We have to create a custom effect for the jquery cycle plugin. Which is minor tweak from the scrollhorizontal effect
You can find the code below; add this to your web page as well

$.fn.cycle.transitions.scrollHorzTouch = function($cont, $slides, opts) {
	$cont.css('overflow','hidden').width();
	opts.before.push(function(curr, next, opts, fwd) {
		if (opts.rev)
			fwd = !fwd;
 
                positionNext = $(next).position();
                positionCurr = $(curr).position();
 
                $.fn.cycle.commonReset(curr,next,opts);
                if( ( positionNext.left > 0 && fwd ) || ( positionNext.left <  0 && !fwd ) )                 {                     opts.cssBefore.left = positionNext.left;                 }                 else                 {                     opts.cssBefore.left = fwd ? (next.cycleW-1) : (1-next.cycleW);                 }                 if( ( positionCurr.left &gt; 0 &amp;&amp; fwd ) || ( positionCurr.left &lt;  0 &amp;&amp; !fwd ) )
                    {
                             opts.animOut.left = positionCurr.left;
                    }
                    else
                        {
                            opts.animOut.left = fwd ? -curr.cycleW : curr.cycleW;
                        }
 
	});
	opts.cssFirst.left = 0;
	opts.cssBefore.top = 0;
	opts.animIn.left = 0;
	opts.animOut.top = 0;
};

Step 3: Initialize jQuery cycle plugin and declare the following variables

     var currenSlide = null;
     var slideNumber = 0;
     var currentLeft = 0;
     var sliderExpr;
     var slideFlag = false;
 
 $('#rotating-item-wrapper').cycle({
        fx:     'scrollHorzTouch',
        timeout: 0,
        pager:  '#nav',
        speedIn:   400,
        speedOut:   400,
        slideExpr: 'img',
        next:   '#nextBt',
        prev:   '#prevBt',
        before: beforeSlide,
        after: afterSlide,
        startingSlide: 0
 });

Step 4: We need two function which will be called after and before the slideshow start.

// Call this function before the slide start
function beforeSlide( curr, next , opt )
{
     sliderExpr = opt.slideExpr;
     slideFlag = true;
}
 
// Call this function after the slide start
function afterSlide(curr, next , opt )
{
    currenSlide =  $(next);
    slideNumber = opt.currSlide;
    currentLeft = $(next).position().left;
    slideFlag = false;
}

Step 5: Here is the main part of the slider.

$('#rotating-item-wrapper').swipe({ swipeMoving: function( pageX ){
 
        if( slideFlag ) return; 
 
       // Defines the left position of the current slide
        var newLeft = currentLeft-pageX;
        currenSlide.css('left', newLeft+'px'  );
 
        var $slides = $( sliderExpr, $('#rotating-item-wrapper') );
        var scrollSlide;
 
       // Get the next slide left
       nextSlideLeft =   newLeft &gt; 0 ? newLeft - currenSlide.width(): newLeft+currenSlide.width();
 
// Defines which is the next one
 flag = newLeft > 0 ? -1: 1;
        scrollSlide  = slideNumber + flag;
 
    // handles if it is the starting or ending slide - loops the slides
        if( scrollSlide < 0 || scrollSlide > ($slides.length - 1 ) )
        {
            scrollSlide = scrollSlide < 0 ? $slides.length - 1 : 0;
        }
 
         $slides.eq( scrollSlide ).css('left',nextSlideLeft + 'px' );
         $slides.eq( scrollSlide ).show();
    },
    swipeLeft: function(){$('#rotating-item-wrapper').cycle('next');},
    swipeRight: function(){ $('#rotating-item-wrapper').cycle('prev'); }
 
    });

You can download the whole source code from the below link. Also if you have any other idea please post it here. You can also modify the source code. Take the demo url on your iPhone or Android device.

Download   Demo

 

github button e1355486394525 Jquery Slider for Iphone and Android with Jquery Cycle and Swipe PluginsGit Project Link Download
Jquery slider for Iphone and Android


Tagged , , , ,

Share this to

22 Comments

  1. ThomasApr 5, 2012 at 2:22 pmReply

    Problem, you are not able to scroll back up if an image takes up the full page. You are only able to scroll left and right. Any idea how to fix this?
    BTW, I realy like this tutorial, nice work :)

    • adminApr 5, 2012 at 2:39 pmReplyAuthor

      Hi Thomas, thank you for pointing this out. I have solved this problem you can download modified new-swipe.js file. Slight modification in the code.

      • ThomasApr 6, 2012 at 11:35 amReply

        Thank you very much. I’ve tested this and it worked perfectly. Very good tutorial!

  2. AndresMay 16, 2012 at 7:07 pmReply

    Works perfect for images, but I was trying to make a slider of divs and it has a strange behaviour. Sometimes when you swipe it leaves the next (or previous) slide div halfway, or at other percentage, the thing is it doesn’t go all the way to the next slide.

    I don’t know if I got myself explained, and if there’s a solution to this.

    Thanks, and excellent work.

  3. Connor McSheffreyMay 23, 2012 at 1:11 amReply

    Thanks for putting this together! I had some performance issues on iOS using larger images. I’m working on rewriting portions to use transform3d and hardware acceleration. I’ll follow up when I finish.

    • adminMay 23, 2012 at 7:26 amReplyAuthor

      Thank you so much… please put a comment when you finish

  4. peyMay 29, 2012 at 8:53 amReply

    Thank you very much
    Great plugin
    Well done!!!!!!!!!!!!!!!!

  5. VolkertJul 3, 2012 at 5:49 pmReply

    Is it just me or can’t I edit the edit the height of an image? Can’t find it anywhere ;’)

  6. adminJul 3, 2012 at 8:59 pmReplyAuthor

    You can edit the height.

  7. Rambo chhetriJul 24, 2012 at 8:20 amReply

    Problem, you are not able to move the image after zooming. if i zoom in i cannot move the image instead of this it will goes to next image.
    BTW, I realy like this tutorial, nice work

  8. senthilkumarJul 25, 2012 at 5:43 amReply

    Thank u for this great plugin. But I want to add a instead of image.will it be possible to add a .In that I’m using a chart. If user swipes, charts gets swiped bt not as a image.
    Sorry , If my question is wrong.

  9. senthilkumarJul 25, 2012 at 5:46 amReply

    Thank u for this great plugin. But I want to add “div” a instead of image.will it be possible to add a “div” .In that I’m using a chart. If user swipes, charts gets swiped bt not as a image.
    Sorry , If my question is wrong.

    • adminJul 25, 2012 at 10:45 pmReplyAuthor

      Hi Senthil, You can change it slideExpr: ‘div’,

  10. JoseAug 6, 2012 at 3:56 pmReply

    Hey great tutorial!
    I would like to use this on xhtml, but not sure if it’ll work…
    Currently working on an ebook (ePub, and using iPad) and i want to tap on a picture, make it big, and then swipe to the next…
    Any thoughts? Plz and thank you!

    • adminAug 7, 2012 at 12:52 pmReplyAuthor

      You can use a fancybox along with the slide

  11. nicmareAug 23, 2012 at 1:05 pmReply

    i really love the fact you take my favourite slider script (cycle) and combine it with a touch script. but the touch script is not the perfect solution if you ask me. its cool as long as you just have a small swipe area but on big image areas you cant drag up or down if you are on the slideshow with your fingertip! try labs.skinkers.com/touchSwipe/ instead
    it can handle that situation and is being still developed

  12. adminFeb 23, 2013 at 12:40 amReplyAuthor

    @nicmare: Increase width and height in percentage

  13. PriyaApr 23, 2013 at 11:17 pmReply

    Hello, thank you for the post. I was wondering is there any way to use this for swiping between two or more tables instead of images?

    • adminApr 26, 2013 at 3:36 pmReplyAuthor

      You can change the slideExpr: ‘img’, to table or div what ever you want

  14. LippiMay 25, 2013 at 11:30 amReply

    Hi, is there any way to make Your slider continuous with autostart?

  15. LippiJun 6, 2013 at 8:38 amReply

    I managed it myself :)

    setInterval(function(){
    $(‘#rotating-item-wrapper’).cycle(‘next’);
    }, 5000);

    • adminJun 6, 2013 at 9:07 amReplyAuthor

      Hi Lippi, Thank you for posting the solution here.

Leave a reply

Your email address will not be published. Required fields are marked *

*

About
View Sarath D R's profile on LinkedIn

I am a technology consultant and an entrepreneur focused on the following technologies Java,Spring, Android, Angular, Asterisk, Symfony, Cake , Code-Igniter, Jquery , XAMPP, XHTML, AJAX, MySql, Seo, Web Design, Wordpress, iPhone development.

Today’s Tips
  • Generate Codova.jar file from Phonegap project using ant
  • Google map javascript client  to find the geographic co-ordinates  from  Address or post code
  • Update Android main UI from Webview – Phonegap Plugin
  • Jplayer is not working  with HTC One Android 4.3 version browser
  • Regular expression to validate mobile phone numbers starting with + ( plus ) – php
  • Simple pagination script for PHP
  • Useful adb ( Android Debug Bridge ) commands
  • Change the javascript files url to absolute url – Symfony 1.4
  • Set Http authentication header from Client – PHP / CURL

This site uses cookies from Google to deliver its services, to personalise ads and to analyse traffic. Information about your use of this site is shared with Google. By using this site, you agree to its use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.This site also uses cookies from Google to deliver its services, to personalise ads and to analyse traffic. Information about your use of this site is shared with Google. By using this site, you agree to its use of cookies.

Close