TouchTouch – A Touch Optimized Gallery Plugin

TouchTouch – A Touch Optimized Gallery Plugin

I want to share a little experiment with Tutorialzine readers – TouchTouch. It is a jQuery plugin that turns a collection of photos on a webpage into a touch-friendly mobile gallery. It works on all major browsers (except for IE7 and below) and most importantly is specifically designed with iOS and Android in mind.

Highlights

  • Smooth CSS3 animations and transitions;
  • A responsive CSS interface that fills the screen and responds to changes in device orientation;
  • Preloads photos only when they are needed;
  • Supports swiping through photos;
  • Displays onscreen arrows and listens for arrow key presses on desktop browsers;

TouchTouch relies entirely on CSS3 for animations, which means that transitions are extra smooth on mobile devices (naturally, this also means that you won’t see any on older browsers). Using some clever CSS, the interface automatically adjusts to the size and orientation of the device, with photos growing to fill the available screen estate (test it by resizing your browser window). And with the help of jQuery, going through photos is done by swiping left or right.

On the desktop, you get that same responsive interface and smooth animations. Browsing the gallery there is done either with the onscreen arrows, or the arrow keys on the keyboard.

jQuery touch-optimized gallery

jQuery touch-optimized gallery

How to use

Using it is simple. Drop the touchTouch folder (you can find it in the download under assets/) somewhere in your website folder tree. After this, include touchTouch/touchTouch.css in your <head>, and touchTouch.jquery.js right after the jQuery library. The script depends on jQuery 1.7 or above.

After you do all of this, simply call the gallery as a regular jQuery plugin:

$(function(){

	// Initialize the gallery
	$('#thumbs a').touchTouch();

});

You must pass anchor elements which point to images in their href attributes for the gallery to work. In addition to conveying which images are to be displayed in the gallery, this also provides a graceful fallback in case JavaScript is not available.

Following Tutorialzine’s tradition of releasing quality resources for developers, the gallery source code is extensively commented and released on Github.

Join our newsletter and get our PSDs!20,184 people learn about HTML5, JS and more. Join them!

by Martin Angelov

Martin is a web developer with an eye for design from Bulgaria. He founded Tutorialzine in 2009 and it still is his favorite side project.

80 Comments

  1. Julius says:

    Great work guys, this function is awesome!

  2. Another stunner. This will be featured on www.jquerythisplugin.com if that is okay. I will also be looking to use it on my own personal website! Great job Martin.

  3. George says:

    Awesome plugin!

  4. Cheri says:

    Can this be used on WordPress sites?

    1. Get!em says:

      Yes it can. See my website.

      Steps:
      1) Download touchtouch
      2) Upload the complete folder into your wordpress blog plugins folder using ftp (or "file browser" plugin of wordpress)
      2) Edit your header.php from your theme and add the CSS line found in the sample index.html (copy the line with touchtouch.css)
      3) Edit the path of the touchtouch.css to match the folder where you uploaded it. (something like www.yoursite.com/wp-content/plugins/touchtouch/assets/touchtouch/touchtouch.css )
      4) Edit your footer.php and include both lines of script
      5) Edit the path of the .js files to match your site
      6) Edit the script.js inside the touchtouch assets folder: replace the "thumbs a" by '#gallery-1 dl dt a' (assuming that you only have 1 gallery per page)

      Make sure that you have references the jquery for your wordpress site, but most will have this already.
      If noConflict is used, replace all $ signs in the javascript files by the word: jQuery

      Its not easy if you didnt see php code before, dont try it then.

      1. Oz says:

        Hi!

        I´m trying to follow your guide but I got lost on step 4. Which 2 lines of script am I supposed to insert into my footer.php and where?

        1. Get!em says:

          Excuses for being not clear enough.

          Step 4 should be:
          Edit your single.php, and place just above the reference to footer.php

          <script src="http://yoursite/yourpath/touchtouch/assets/touchTouch/touchTouch.jquery.js"></script>
          <script src="http://yoursite/yourpath/touchtouch/assets/js/script.js"></script>

          Extra, adding a close button (see my website)

          1)Edit the Touchtouch.jqueri.js
          1a) Add a closebutton
          /* Private variables */

          var overlay = $('<div id="galleryOverlay">'),
          slider = $('<div id="gallerySlider">'),
          prevArrow = $('<a id="prevArrow"></a>'),
          nextArrow = $('<a id="nextArrow"></a>'),
          closebutton= $('<div id="closebutton"></div>'),
          overlayVisible = false;

          1b) add the button to the overlay
          // Appending the markup to the page
          overlay.hide().appendTo('body');
          slider.appendTo(overlay);
          closebutton.appendTo(overlay);

          1c) add close function to button
          // Hide the gallery if the background is touched / clicked
          slider.append(placeholders).on('click',function(e){
          if(!$(e.target).is('img')){
          hideOverlay();
          }
          });
          closebutton.on('click',function(e){
          if(!$(e.target).is('img')){
          hideOverlay();
          }
          });

          2) create or download a close.png image and upload it to your touchtouch folder
          3) Edit the touchtouch.CSS for the close button
          #closebutton{
          /*-webkit-border-radius: 15px;
          -moz-border-radius: 15px;
          border-radius: 15px;
          border: 2px solid #666666;
          float: right;
          font-size: 1.5em;*/
          background:url('close.png') no-repeat;
          height: 25px;
          /*line-height: 25px;*/
          position: absolute;
          right: 10px;
          top: 10px;
          width: 25px;
          cursor: pointer;
          z-index = 5;
          background-position-x: -10px;
          background-position-y: -10px;
          }

          Edit the width, height, right, top and background-position values to your taste and your image will be placed right.

          1. Get!em says:

            3) Edit touchtouch.css but more simple and without comments:

            #closebutton {
            background: url("close.png") no-repeat scroll 0 0 transparent;
            cursor: pointer;
            height: 45px;
            position: absolute;
            right: 10px;
            top: 10px;
            width: 45px;
            }

          2. Get!em says:

            Small addition, not 100% failsave, but works good enough for me: Hide previous and next buttons on first and last image.

            buttonsnextprevious step 1)
            touchtouch.css
            add new line:

            .notvisiblebutton{
            display:none;
            }

            buttonsnextprevious step 2)
            Edit touchTouch.jquery.js

            Look for the lines below and see changes

            function showImage(index){

            // If the index is outside the bonds of the array
            if(index > 1 && index < items.length){
            prevArrow.removeClass('notvisiblebutton');
            nextArrow.removeClass('notvisiblebutton');
            }
            if(index < 0 ){
            prevArrow.addClass('notvisiblebutton');
            return false;
            }

            if(index >= items.length){
            nextArrow.addClass('notvisiblebutton');
            return false;
            }

            // Call the load function with the href attribute of the item
            loadImage(items.eq(index).attr('href'), function(){
            placeholders.eq(index).html(this);
            });
            if(index == 0){
            prevArrow.addClass('notvisiblebutton');
            nextArrow.removeClass('notvisiblebutton');
            }

            }

  5. WSDR says:

    Very cool, I'll try and use this on a mobile site soon.

  6. Umar says:

    But how to have 5 thumbs in a line instead of 3?

  7. André says:

    Runs pretty smooth on my HTC Desire Z. Preloader works great!

  8. SMBR says:

    Totally, aWesome

  9. ramzesimus says:

    Hi! Have you tested this awesome plugin on iPhone or iPad? I have some bugs when displaying on iPhone :( If you click on thumbs the fullscreen gallery displays only on the top of the screen.

    1. Martin Angelov says:

      This shouldn't happen. Which iOS version are you using?

      1. ramzesimus says:

        I'm on iOS 4.2.1.
        I've tested on 5.x using another iPhone and it works great.

        1. Martin Angelov says:

          After a short research it appears that this is caused by earlier Mobile Safari versions not supporting fixed positioning. If somebody has a 4.2 device handy and is willing to fix it, read this github issue.

    2. Dirk-Jan says:

      seems like this is not only a problem with the iphone but with a lot of android based mobile's cause most of the browsers don't support fixed positioning, I fixed this by first letting the user scroll to the top through a jquery command. You can achieve this by adding 1 line of code to the "function showOverlay(index)" I believe this function is around line 130-160 best is to put it after:

      if (overlayVisible){
      return false;
      }

      and add this line of code under the }

      $('html, body').animate({ scrollTop: 0 }, 0);

      it is not very nice though to let it scroll to the body of your page. It would be better to find a element (I guess a div would work) which is on the absolute top of your page and let it scroll to that div. I'm sure google can help people further on that one.

      1. Ian says:

        Thanks for this! Simple, quick and effective.

  10. LESTER says:

    One of the best swipe touch gallery thats out there! How can I add social buttons beneath every picture in the galleryOverlay? I am not that good in javascript. I am trying to add a div in touchtouch.jquery.js, dont how this is done....need help please.

    1. Martin Angelov says:

      This would involve modifying a lot of the plugin code and this would also clutter the interface. Wouldn't it be better to simply show one set of like buttons on the page itself?

      1. LESTER says:

        Yes you could, but I thought it is more convenient for users to like in the galleryOverlay while swiping pictures. Now they have to go out the "lightbox" to like a picture (page)....ah well

  11. Terry says:

    Amazing plugin!

  12. Elie Andraos says:

    WoW ! this is very impressive ! great work ! i have tried it on my ipad :)
    One question thought, does it support embedded youtube videos ?

    1. Martin Angelov says:

      Not at this time. It would have to use HTML5 video embedding.

  13. Just a quick FYI, this works great in iPad/iPhone, but on my HTC Sense, every gallery hangs in landscape when i get to the tall image in the demo titled "The Pond"; switching to portrait clears it to swipe again. Think it's a height issue?

    Cheers,
    Atg

  14. Andre says:

    Pretty nice work guys, you rock!!!

  15. elmerz says:

    Can the image loop instead of stopping at the end?

    Thanks

    1. mamikon says:

      You need to modify two things in touchTouch.jquery.js:

      1. Put two new lines near the line 87 in the original file:

      preload(0);
      preload(items.length-1);
      

      2. Modify the ShowNext and the ShowPrevious functions:

      function showNext(){
      	
      	// If this is not the last image
      	if(index < items.length-1){
      		index++;
      		offsetSlider(index);
      		preload(index+1);
      	}
      	else {
      		index=0;
      		offsetSlider(index);
      		preload(index+1);
      	}
      }
      
      
      function showPrevious(){
      	
      	// If this is not the first image
      	if(index > 0){
      		index--;
      		offsetSlider(index);
      		preload(index-1);
      	}
      	else {
      		index=items.length-1;
      		offsetSlider(index);
      		preload(index-1);
      
      	}
      }
      

      It makes not a smooth transition, but works.

  16. elmerz says:

    Hi Martin,
    I have tried this with my droidX and the swipe only shows up on top of the page. Is there a solution for this?

    Thanks,
    EB

  17. crisscross says:

    Hi Martin, awesome script!!! thx for this.
    Is it posible to show the link-title below the picure in the gallery?
    Chris

    1. TheJosh says:

      Yeah, looking at figuring out how to pull the title attribute from the image as well. Would be amazing if that's possible.

      - Josh

  18. Emilie says:

    Hi ! This is a great plugin.
    Though I'm having trouble to set multiple galleries within the same page. Is it possible ?
    Thanks
    Emilie

  19. Adrian says:

    This is great.
    I tried several mobile galleries like photoswipe or others but every single one of them doesnt work with all devices. This one does. Thanks!

  20. Omar Chavira says:

    Great gallery, I tried several and this is the only one that I actually liked. Just a question. Is there a way to have a close button in the slideshow? Because if the user clicks the "back" button in the browser, some wonky stuff happens.

  21. Omar Chavira says:

    When I implement this in a mobile website with jquery mobile, it works perfectly when viewed on a desktop browser, but when I switch to a mobile device, it stays in "loading" forever. I've determined the culprit es jquery mobile because when I remove it from my page, everything works. Is there a workaround for this that doesn't involve not using jquery mobile? I've tried appending rel="external" and data-ajax="false" to my anchor tags but it doesn't work.

    1. Steve says:

      The selector may be grabbing other links that are not images.

  22. Neil says:

    Testing this and on a HTC One X resolution 1280 x 720, in both landscape and portrait we are getting slightly blurred images. Our images are 500 x 500 optimised for clarity. Any ideas?

  23. James says:

    Great tutorial. Is there a way to add multiple galleries on one page? Thank you.
    -James

  24. Achilleas says:

    Perfect gallery, but is there a way to have multiple galleries in the same page and not showing all the imgs of the page?

  25. kevin prendergast says:

    Hi Martin,

    Great plugin! I have altered it a bit to allow multiple galleries on one page and also to allow divs to be displayed instead of just images if you would like the edited code.

    thanks,
    Kevin

    1. MarkL says:

      Hey, please send the updated code. Thanks.

    2. chris says:

      Kevin: I'd very much like your updated code. Pls. e-mail ZIP file to sleepycg at gmail. Thx!

      1. Chrissy says:

        Hey Chris - did you get the updated files for multiple galleries?

    3. Beat says:

      Hi Kevin,

      could you share with us this modified code? It would be great to use/add any kind of content and create separate galleries for each thumb. With these features the plugin would be rounded!

      I hope you can help with it!

      Thanks!

  26. chris says:

    What would be the init script to use multiple lightboxes on one page?

  27. Feantury says:

    Hey Martin, I've done some modifications on your plugin that makes it compatible with jquery mobile applications (also desktop of course) and ajax development. There is moreover an improve for tap events on external images, and change on <a> buttons to <img>, I think it's more intuitive.

    If you want to take a look to this code and add it ask me on the email of this comment.
    ;)

    1. Daryl says:

      Feantury, I have been trying to get this to work with jQuery Mobile 1.2 with AJAX calls to no avail. Can I try your version?

    2. Cibulka says:

      Feantury, I know it's been a year, but I am struggling to get TouchTouch script to work on content loaded by jQuery load function as well. Did you ever resolve that issue?

      Thank you very much! cibulka.me[at]gmail.com

  28. John says:

    Thanks a million! Been looking for this and you just saved the day!

  29. Jay Patel says:

    Works great!! Thank you for a fantastic plugin.

    Is there a way to overlay title of the images?

  30. Thai Hoc Vu says:

    If the image fit to the screen, i can not close the current image to back gallery :(

    1. Feantury says:

      This could be fixed by modifying the css on:
      #gallerySlider .placeholder{
      background: url("../img/preloader.gif") no-repeat center center;
      height: 90%;
      line-height: 1px;
      text-align: center;
      width:90%;
      display:inline-block;
      }

  31. Dirk-Jan says:

    Excellent script! However there is 1 thing i changed and that is the ability to close the gallery with a button. This was actually pretty easy to accomplish so to help other people here a little how to:

    on line 17 in touchTouch.js add :

    closeGallery = $('<a id="closeGallery"></a>'),

    (wont be to hard it will look like the other var's)

    Now the following code can be added anywhere in the .js document but I prefer to place it at the end (around line 237)

    //ownmade: hide the gallery on click on this div
    closeGallery.appendTo(overlay);
    closeGallery.click(function(e){
    overlay.hide().removeClass('visible');
    overlayVisible = false;
    });

    And finally to make it look great is to add a new part to the touchTouch.css:

    #closeGallery{
    width: 58px;
    height: 58px;
    background:url('close.png') no-repeat;
    position:absolute;
    right: 10px;
    top: 10px;
    opacity:0.5;
    z-index: 99;

    border:none;
    text-decoration:none;
    cursor:pointer;
    position:absolute;

    -moz-transition:opacity 0.2s ease;
    -webkit-transition:opacity 0.2s ease;
    transition:opacity 0.2s ease;
    }

    also change line 127 ( #prevArrow:hover, #nextArrow:hover { ) to this:

    #prevArrow:hover, #nextArrow:hover, #closeGallery:hover{

    Now you should have a div at the top right of your screen (I also tested it on my mobile and it also showed up) the only thing you need to do is add a image to the touchTouch folder called "close.png".

    Hope this will help some people!

    1. Shimal says:

      Thanks Dirk-Jan!
      Do you know if it is possible to close the gallery with the escape button?

      1. Amos says:

        Shimal - add these lines at line 121:

        			else if (e.keyCode==27){
        				hideOverlay();
        			}
        

        Dirk-Jan - instead of using:

        overlay.hide().removeClass('visible');
        overlayVisible = false;
        

        you should use:

        hideOverlay();
        
        1. Arno says:

          Can you be more specific where to put code for the escape button, because I already adjusted the file with the comments above. And the place I thought it should be, is not going write.

  32. Hi! How can I put videos in the jquery????

    thanks a lot!

  33. Justen says:

    Any way to add a simple black banner at the bottom with some captions on the photos?

    Thanks,

  34. moataz says:

    I need to put the scripts in the head section but the plug in is not working after that because i'm using it with asp.net and put the scripts in the master page at header .

  35. Patrick says:

    hi,
    the touchtouch on my site don't seem to work well in chrome android, the bigger images don't show up. any idea ?
    thanks

  36. Beat says:

    I would like to know if what point is this plugin in development. I really love the smooth transitions and I think this engine has a lot of potential, but it is a pity that the plugins does not support videos from youtube or vimeo.

    Does anyone have a good solution for this problem?

    If within the gallery we could use any kind of content it would be almost perfect. Any advice in this way would be very grateful!

    Thanks in advance and very good work, Martin!

    :)

  37. Laura says:

    Hello,
    Great plugin, thanks for sharing. Was wondering how to add caption / title for image once it's displayed in gallery? There is some info in github, but found it to unclear.
    Thanks.

    1. Amos says:

      The script in the demo is based on CSS displaying the value of the title attribute of each image, and I think that's a great solution.

      Just make sure you have a 'title' attribute for each link and add these CSS rules:

      #thumbs a::after {
      	background-color: #303030;
      	border-radius: 7px;
      	bottom: -136px;
      	box-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
      	color: white;
      	content: attr(title);
      	display: inline-block;
      	font-size: 10px;
      	max-width: 100px;
      	min-height: 8px;
      	overflow: hidden;
      	padding: 2px 10px;
      	position: relative;
      	text-align: center;
      	white-space: nowrap;
      }
      
  38. Bernardo Santos says:

    Is there a way to add multiple galleries on one page? Thank you. Bernardo

  39. Really love this gallery!

    But I can´t make it work on multiple galleries. It just continues to show all the images, see source code on my mobile site. What am I doing wrong? Code goes
    <ul class="thumbs" data-gallery="one">....</ul>
    <ul class="thumbs" data-gallery="two">....</ul>
    <ul class="thumbs" data-gallery="three">....</ul>

    And it makes IE on desktop hang. Which is a shame, I´d really like to use it on my desktop site as well

  40. James says:

    Is there a way this code can be altered so it will attach itself with content loaded via ajax? I'm using this gallery on a Drupal installation (which has some built in ajax in views), everything works great until the content is loaded with ajax, the gallery fails to work. Am I looking at this the correct way?
    Thanks,
    James

  41. LAOMUSIC ARTS says:

    Thanks for the tut buddy!
    This doesn't work inside jQuery Mobile though.
    Any suggestions?

    Thanks for any help !

  42. Matt Day says:

    Some notes for people wanting to use this on their sites:

    1. Problem with multiple galleries:
    To reproduce the problem, change example-multiple-galleries.html so that the second gallery has the data-gallery="two" attribute in the parent div and not in each element. To fix the problem, change the block of code after line 118 to:
    items = $closestGallery.find(items);

    2. jQuery noConflict:
    If you use noConflict (e.g. a WordPress site), do not change all the $ in the script, simply change the first line from (function(){ to (function($){

    3. Future development and maintenance:
    There is so much interest in this excellent plugin - I hope we can get a repository set up, so things can be fixed and added only once, not by many developers independently. Hope to hear from Martin in this respect.

    4. WordPress plugin:
    I have developed a simple gallery plugin to add pagination and use TouchTouch for display. I will post details when a beta is available here.

    Thanks,
    Matt

    1. Makdas says:

      Brilliant Matt, thanks

  43. Nik says:

    Thanx very much for superb plugin!
    I have a question:
    - How can show photo's title (description) when it show?

  44. Dave says:

    I can't get it to work with Quicksand, sadly, since I can't figure out how to refresh the photo index after filtering the pictures; if anyone knows how to do that, let me know!

  45. jollysod says:

    Terrific plugin.
    Had a bit of an issue with ie not respecting aspect ratios of images when resizing the window.
    Found an answer here:
    (http://stackoverflow.com/questions/3642541/max-width-and-max-height-for-scaling-images-in-internet-explorer).
    Quick fix: add "width:auto" and "height:auto" to touchTouch.css...

    #gallerySlider .placeholder img{
    	display: inline-block;
    	max-height: 100%;
    	max-width: 100%;
    	height:auto;
    	width:auto;
    	vertical-align: middle;
    }
    

    Hope this comes in handy,
    JS

  46. Kane Ford says:

    How do I make it so the captions beneath each image can be longer than 1 line? I set white-space:auto in .thumbs a:after but the captions overlap the thumbnails that are below. :\

  47. Rai says:

    Hello Martin,

    first i want to say "Thank you" for this nice plugin.

    I have used TouchTouch on a Website and get the same problem like:
    https://github.com/martinaglv/touchTouch/issues/1

    Changing
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    to
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, maximum-scale=1.0" />

    have fixed the problem by me.

    tested on Samsung Galaxy Ace and Motorola Defy+

  48. Szymon says:

    Its doesnt work on maxthon:/ , besides its perfect ! :)

  49. Rex Quadry says:

    Hi,
    Really nice work you've done with this plug-in. I do have a problem though, i'm making use of it in a mobile app alongside jquery mobile and backbone.js. The app has multiple image galleries, and i call the touch-touch method on each one, the problem is that after closing one gallery and opening a new one, the plug-in retains the pictures from the previous gallery, hence, the first sets of images are from the previous gallery(ies), and if the previous gallery or set of galleries have more images than the current one, you don't get to see any of the mages in the gallery has it creates placeholders for the number of items in that gallery.
    I will like to eraze all instances of placeholders once the "hideOverlay()" method is called after clicking outside the image, so that with a new gallery in place, it has a fresh set of placeholders.
    Thanks in advance

  50. Ondrej says:

    Hi, a perfect plugin, but I am really missing a simple way of adding captions underneath the images. There are a few users here, who have already asked for this functionality, but I don't see any answers. Could you please help with this minor issue to an otherwise great plugin?

    Thanks a lot in advance.

  51. Hi Martin, thanks for this plugin! My first choice was photoswipe, but using that one on my gallery had some quirks on my Android, so I used yours instead. Simple, lightweight, exactly what it needs to do.

    But I made some updates to your code, which enables it to be re-run on a gallery after re-arranging photos (I use a sortable() on my gallery so people can rearrange the order of the photos). Also the ESC key has been added, courtesy of Amos in the comments.

    Where should I send the diff to?

  52. Wouter says:

    Hi Martin, it's me again :) It'd be pretty cool if you exposed event handlers for when a user browses through the image gallery. I'll probably hack it up into the plugin, just giving you ideas.

Add Comment

Add a Reply

HTML is escaped automatically. Surround code blocks with <pre></pre> for readability.
Perks:   **bold**   __italics__   [some text](http://example.com) for links