Friday, March 30, 2012

Using the PhotoSwipe Image Gallery Script

This tutorial is in response to a specific request by someone who wanted to know how to implement the PhotoSwipe Image Gallery script into a mobile JQuery website. Here's a link to PhotoSwipe for some context and a download link of the script for yourself:

http://www.photoswipe.com/

Here is a link to what our final product will be - you should test it out:

http://thecodingwebsite.com/tutorials/photoswipe/photoswipe.html

I basically just used their code examples and example images and removed all of the unnecessary code and such to determine the essential parts needed for a mobile JQuery website implementation. If you would like to just download my working example as a whole, I have placed it into a zip file for you:

http://thecodingwebsite.com/tutorials/photoswipe.zip

Now that all of that is established, I will explain the necessary parts of this implementation so you can do it to your own website. First, we'll start with an empty HTML-structured file:

<html>
 
<head>
 
</head>
 
<body>
 
</body>
 
</html> 

Next, you'll need to include two CSS stylesheets, JQuery Mobile (which should already be in your web pages from my understanding of JQuery Mobile) and "photoswipe.css" (included in both PhotoSwipe's download and my download):

<head>
 
<link href="http://code.jquery.com/mobile/1.0rc2/jquery.mobile-1.0rc2.min.css" rel="stylesheet" />
<link href="photoswipe.css" type="text/css" rel="stylesheet" />
 
</head>

Then you'll need to include 4 script files, "klass.min.js" (a library that PhotoSwipe uses), JQuery and JQuery Mobile (which may both be included in your website as well), and "code.photoswipe.jquery-3.0.4.min.js" (PhotoSwipe itself):

<head>
 
<link href="http://code.jquery.com/mobile/1.0rc2/jquery.mobile-1.0rc2.min.css" rel="stylesheet" />
<link href="photoswipe.css" type="text/css" rel="stylesheet" />
 
<script type="text/javascript" src="klass.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.4.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/mobile/1.0rc2/jquery.mobile-1.0rc2.min.js"></script>
<script type="text/javascript" src="code.photoswipe.jquery-3.0.4.min.js"></script>
 
</head>

All of the included files have been placed in the header of the page. It's important to make sure of that. There is one last piece of code that you'll have to place in the header (to active PhotoSwipe) before we can move on to the images themselves. Apologies for the poor spacing of the JQuery code... It's not saving my tabs properly =]:

<head>
 
<link href="http://code.jquery.com/mobile/1.0rc2/jquery.mobile-1.0rc2.min.css" rel="stylesheet" />
<link href="photoswipe.css" type="text/css" rel="stylesheet" />
 
<script type="text/javascript" src="klass.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.4.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/mobile/1.0rc2/jquery.mobile-1.0rc2.min.js"></script>
<script type="text/javascript" src="code.photoswipe.jquery-3.0.4.min.js"></script>
 

 
</head>

Notice that the photoSwipe method call is placed on all <a></a> elements with a parent id of "gallery" - we'll need this information to code in our images properly.

The HTML body code is relatively simple yet redundant:

  

The id of the div containing all of the images is "gallery", just like in the JQuery code above. Each image is surrounded by an <a></a> (link) tag with an "href" (link destination) property set to the location of the full size image and the "rel" property set to "external" (PhotoSwipe's mobile JQuery examples say this is important - I am not familiar with mobile JQuery myself so all I can say is that I recommend you set "rel" to "external" :).

Inside each <a></a> tags are the actual image elements themselves, with their source set to the location of the thumbnail version of each image.


One last comment I should make about using PhotoSwipe: all of the files I included in the zip folder are necessary. Obviously the images themselves can be replaced by your own, the PhotoSwipe code can be updated, the "photoswipe.html" file will be replaced with your own website with the code I explained above included, etc. However, you will need the following files (at least) in order to use everything:
  • Full size and thumbnail size versions of each image
  • "icons.png" and "icons@2x.png" - these are for e.g. the left/right and close buttons when you click on an image
  • "klass.min.js" and "code.photoswipe.jquery-3.0.4.min.js" - the JavaScript include files
  • "photoswipe.css" - also necessary to use PhotoSwipe
  • The JQuery and JQuery Mobile scripts, unless you plan on referencing to them on the JQuery website like I did in the examples above

Now you are set up to use the PhotoSwipe Image Gallery script on your mobile JQuery websites. Enjoy! :)

69 comments:

  1. This helps so much, thank you for making this tutorial! :)

    ReplyDelete
  2. No problem, and thanks for the feedback!

    On a side note: I just checked the photoswipe link on my website, and it wasn't working. Somehow it must have been deleted or something. I put everything back up though!

    - Andrew

    ReplyDelete
  3. Hello,

    How do you do in http://thecodingwebsite.com/tutorials/photoswipe/photoswipe.html to open the first image of the gallery without clicking in the image?

    Thanks in advance!
    Cheers,
    Jose.

    ReplyDelete
    Replies
    1. Good question! I must have modified it later and then forgot to explain that part. If you look at the source code of that page (hotkey Ctrl + U in Firefox):

      (function(window, $, PhotoSwipe)
      {
      $(document).ready(function()
      {
      $("#gallery a").photoSwipe(
      {
      enableMouseWheel: false,
      enableKeyboard: false
      });

      $("#gallery a:first").click();
      });
      }(window, window.jQuery, window.Code.PhotoSwipe));

      You can see this line here:

      $("#gallery a:first").click();

      This selector gets the first *child* "a" (link) element that's inside the element that has an id of "gallery" (in this case, the "div" containing all of the links/images), and then it simulates a click of that link.

      - Andrew

      Delete
  4. Hey Thanks for tutorial

    But is there any way to make it work on dynamically added images

    ReplyDelete
    Replies
    1. Thank you!

      I would think you could. You may have to call photoSwipe again *after* new images are added or etc., but yeah, you'll just have to try it and see.

      - Andrew

      Delete
  5. hi there, I use it for rubyonrails website, but for some reason, it need to refresh the page before the photoswipe start:
    site add: http://prod.computersforpeople.info/users/262/properties/47198

    when you click on the photo, it will link to the photoswipe page, but it won't start until you refresh the page.
    could you help please

    ReplyDelete
    Replies
    1. It doesn't work for me at all in Firefox.

      From a quick glance at your code though, I don't see this surrounding your images (with the triangle brackets of course):

      div id="gallery"
      /div

      - Andrew

      Delete
    2. sorry, I might just editing it make it not work,
      try again, click on any photo, then refresh, the photoswipe will work after that,
      how can I start it without refresh please
      many thanks

      Delete
    3. No, I told you it still doesn't work.

      - Andrew

      Delete
    4. Try this one: http://prod.computersforpeople.info/users/262/properties/47195
      Click on the photos then refresh the page.
      cheers

      Delete
    5. how did you fix the issue? i still have to refresh the page just to make the photoswipe work

      Delete
  6. Any views on best size for thumbnail images? It seems wasteful to have anything bigger than say 100x100 when they are going to be minute on the mobile screen anyway.

    ReplyDelete
    Replies
    1. It depends on what devices/audience you're targeting and how much of the picture they'll need to be able to see in the thumbnail. I would figure out the smallest screen resolution that you're targeting and do a little math and maybe some testing so that it looks good.

      You could also try to make your thumbnails bigger and then scale them down to the size of the phone, whatever that size would be.

      - Andrew

      Delete
  7. Hi - Is there a way to have the caption show when using the slide show feature?
    -Josh

    ReplyDelete
    Replies
    1. Hello,

      If you don't see it as an option at the bottom of photoswipe.com (in the "Configuration" section) then you'll have to ask PhotoSwipe about that. You might be able to do it yourself (manually), but that could be tricky.

      Sorry,

      - Andrew

      Delete
  8. Hi Andrew,

    sorry to disturb you. can you please tell me where should i place the icons.png" and "icons@2x.png, error.png i am confuise, i have put them image folder ( e.g my html file is in maruf. i have created a image folder called maruf/image. so i put the icons.png, icons@2x.png there. when i run the slideshow those button are not visable. dont know what to do. please help.

    i really do appreciate for your help.

    ReplyDelete
    Replies
    1. Photoswipe expects those images to be in the same folder as the script. If you absolutely want those images to be in "maruf/image/", you'll need to open "photoswipe.css" in Notepad and replace "icons.png" with "maruf/image/icons.png" and etc. for the other images.

      - Andrew

      Delete
    2. Thanks for your help.

      Delete
  9. Hi Andrew,
    Great tutorial for the photoswipe.

    I am having some problem with the navigator button.

    I go to "photoswipe.css" to change the navigator icon location but it still not show in website when I clicked the thumbnails.

    Can I ask what us the problem?

    Thanks

    ReplyDelete
    Replies
    1. Thank you!

      Well, first of all I'll make sure to remind you that you need to re-upload the CSS file back onto the website - just in case. :P Also make sure that it really is using the file you upload as opposed to one in a different folder that you're not seeing or anything.

      I believe for PhotoSwipe the CSS file is the sole decider of the icons and etc., so all I can recommend is that you make sure there aren't several instances of the navigator icon in the CSS file, there aren't multiple copies (maybe of different sizes) of the navigator icon, or etc.

      - Andrew

      Delete
  10. Howdy Andrew,

    In the Photoswipe demo, they show thumbnails that respond to the size of the screen - in other words the smaller the screen the smaller the thumbnails get. Using your tutorial, this doesn't seem to work. What needs to be added or changed to get this to work? This might be beyond the scope of your tutorial, but I thought I'd ask. I appreciate your time :)

    ~Matt

    ReplyDelete
    Replies
    1. I suspect it is not Photoswipe related. Try commenting out your Photoswipe code for now and work on just the HTML aspect of it.

      It appears they're using an unordered list HTML element around their images:

      http://www.w3schools.com/tags/tag_ul.asp

      Try doing the same - place the "ul" tags inside the gallery "div" and then surround each image link with an "li" element.

      - Andrew

      Delete
    2. You're right. It's not a photoswipe issue. (Guess I should've looked into that first) I found some custom css they loaded in the headed in addition. Yet, I've tried that and still can't get the result. I literally have photos with bullet points next to them. lol. Thanks for the help though.

      Delete
  11. Great tutorial!

    I am having a tough time specifying a target into a mobile JQuery website.

    This the code I am using to set up PhotoSwipe:
    (function (window, $, PhotoSwipe) {

    $(document).ready(function () {

    var options = { target: document.getElementById('PhotoSwipeTarget') };
    $("#Gallery a").photoSwipe(options);
    });

    }(window, window.jQuery, window.Code.PhotoSwipe));

    Then I am adding this to the body: div data-role="content" id="PhotoSwipeTarget"/div

    This code is not working. When it runs in full screen it works fine. Any suggestions as to what I may be doing wrong?

    ReplyDelete
    Replies
    1. The information you've provided above looks okay, so I'm going to guess that your problem lies within the information not provided above. :)

      Compare all of your code (including the HTML) to mine as strictly as possible. Even try implementing it in such a way that you don't want it to work but also in a way that's more exact in comparison to my code, just to get it to work. Then you should be able to find the problem.

      Also, this should be obvious, but make sure you are including everything and it's all in the right order and such - order matters.

      - Andrew

      Delete
  12. I'm french, sorry for my english:
    I did everything you said in the tutorial. photo gallery works with my computer but not with the mobile phone.
    When I click on a photo, it appears small on a white background (?)

    I repeat: everything works perfectly on the computer. Is it perhaps because the model of phone? (android 4.0.3 Smartphone)

    ReplyDelete
    Replies
    1. It sounds like it could be an HTML/CSS problem. To ensure this, I would place an alert in a critical section of JavaScript code to make sure that it is being reached on the phone.

      Try to find out what browser and version the phone is using, and then see if you can test out the web page and check if there are any errors with that specific browser.

      - Andrew

      Delete
  13. the phone is not mine
    It has lent me for testing.
    but I'll try another phone later to see if the problem persists. and I'll tell you what happens.

    thank you for your quick response ...

    ReplyDelete
  14. I just tried with a Samsung Galaxy note2, bought yesterday, and there is the same problem.
    So it is not because of the phone.
    I do not understand where the problem may come

    ReplyDelete
    Replies
    1. Do some research and determine what browser and version these phones are using.

      - Andrew

      Delete
  15. the samsung is a new phone...

    ReplyDelete
  16. Replies
    1. I don't understand what you mean by "long description" exactly. Changing the "alt" tags will change the title of each picture at the top. If you're asking about something else, you'll need to be more specific.

      Delete
  17. i mean in my application every image have description so how to add description.and there something is called image-meta-data.and one more question when i am clicking on image don't want to hide toolbar

    ReplyDelete
    Replies
    1. I still don't know what you're asking.

      You can read about metadata here:

      http://en.wikipedia.org/wiki/Metadata

      If what you're wanting to do is integrated into PhotoSwipe and PS doesn't provide an option for it (options are listed on their website) then you'll have to take your case up with them because they made it.

      Delete
  18. Hello ,

    Thank you for the great tutorial.
    May i explain my problem here?
    I am using Photoswipe gallery with jQuery Mobile. The first selection, when clicked/tapped shows just the image with full URL and does not work the gallery way. When I go back and select again, it works fine.The ps is working after a first failure/refresh of page.
    I found some solutions in net such as :



    (function(window, $, PhotoSwipe){
    $(document).ready(function(){

    var activePage = $('.ui-page-active');

    options = {},
    photoSwipeInstance = $("ul.gallery a", activePage).photoSwipe(options, activePage.attr('id'));

    $('div.gallery-page')
    .live('pageshow', function(e){
    var currentPage = $(e.target),
    options = {},
    photoSwipeInstance = $("ul.gallery a", e.target).photoSwipe(options, currentPage.attr('id'));

    return true;
    })
    .live('pagehide', function(e){
    var currentPage = $(e.target),
    photoSwipeInstance = PhotoSwipe.getInstance(currentPage.attr('id'));

    if (typeof photoSwipeInstance != "undefined" && photoSwipeInstance != null) {
    PhotoSwipe.detatch(photoSwipeInstance);
    }

    return true;
    });
    });

    }(window, window.jQuery, window.Code.PhotoSwipe));


    But it is not working for me :( !
    Can you please tell me how can I sort this out?

    regards,
    Harikris

    ReplyDelete
    Replies
    1. Perhaps the page is not yet loaded. Have you checked for this? (Wait a couple of seconds, etc.)

      It doesn't make sense that it would only work after refreshing... What browser are you using? Does it work in other browsers?

      - Andrew

      Delete
  19. Please check the link below.it's my mobile website.
    http://w3qatar.info/aldarmobi

    When we check the link Properties> any property from the list > View more photos ... under this you can find the thumbnails. When we click the thumbnail first it will load the original image without gallery view.But when we go back and try again ,it will work.i'm using opera mobile emulator for testing. Drupal 7 with Mobile_jquery theme. Jquery mobile is used in this site.

    Could you please help me?
    I want to work this in iPhone devices and android phones.

    thanks in advance.

    harikris.

    ReplyDelete
    Replies
    1. I am seeing the same result in Internet Explorer.

      In Firefox, however, it never works properly and there are 2 errors occurring when the page loads:

      Error: ReferenceError: $ is not defined
      Source File: http://w3qatar.info/aldarmobi/al-thumama
      Line: 24

      Error: TypeError: window.Code is undefined
      Source File: http://www.redstonephotography.com/mobile/js/javascript.js
      Line: 58

      Go download Firefox and try developing your website without errors.

      - Andrew

      Delete
  20. i'm sorry ,i was trying some other codes when you were testing my site.I have cleared the above mentioned errors and i found new error "uncaught exception:Code.PhotoSwipe.createInstance: No images to passed".

    This is only for first time page load.
    Could you please check it?Please help me to find a solution.

    ReplyDelete
    Replies
    1. That error is not related to the one on the page that's not working properly (it's being generated on the home page).

      You used the "ul" rather than the "div"; that won't work. You should be able to leave the "ul" in there, but move the "id" property over to the "div".

      In the future, always make sure to follow the details in tutorials exactly when something doesn't work properly.

      - Andrew

      Delete
  21. I am using this gallery here
    http://www.techbrainzwebsolutions.com/portfolio/mybagspa/gallery.php
    i want to call a div consist of 2image so that when user click on the thumbnail
    there will be two image sidebyside, is this possible.
    Thanks
    support@techbrainzwebsolutions.com

    ReplyDelete
    Replies
    1. This doesn't seem doable with Photoswipe. You could try using frames, but this would take a lot of JS work.

      - Andrew

      Delete
  22. hii iam using Photoswipe gallery in my project., i need to save the image to local storage . Is this possible to save the image that using Photoswipe Gallery in mobile jquery. thanks in advance..

    Regards,
    Suresh

    ReplyDelete
    Replies
    1. You mean save an image of what you see on your screen, aka a "print screen"? or something else?

      - Andrew

      Delete
  23. Hey, thanks for the awesome tutorial. I have a few specific follow up questions as I cannot seem to get the jquery to trigger on image click (rails 3 / JQM stack)

    I see above you offered to make an additional tutorial for someone. If you'd be willing to help us out on a very short deadline, we can pay you what you think is reasonable.

    We are on a very short deadline. I dont think the question would take long, maybe 15 min.. Would even prefer a quick phone call if possible.

    Let me know if you are familiar with rails / would be interested in helping us out. Best.
    Josh
    text / call
    3l5-43O-2926

    ReplyDelete
    Replies
    1. Sorry, I am not. I do make $5 tutorials on coding topics that I am knowledgeable of, however; see this page for more information:

      http://thecodingwebsite.com/requestTutorial.php

      - Andrew

      Delete
  24. Hello,
    i created site with jquerymobile and photo swipe when i connect from my phone is possible setwallpaper on my phone? How?

    Thanks

    ReplyDelete
    Replies
    1. Nope. You'll need to write an app for that.

      - Andrew

      Delete
  25. I have to refresh the page before the photo swipe will work, can you help me fix this issue?

    ReplyDelete
    Replies
    1. 1. Try using a different browser to see if that works.
      2. Try simplifying your web page more like my code until it works fine, and then you will be able to identify the problem.

      - Andrew

      Delete
  26. Thanks for the great tutorial! Made much more sense than the one I was trying before. I am having a few issues, but I am sure I can sort it out. Great people like you make it possible for average people like me to achieve great results!

    ReplyDelete
    Replies
    1. Glad to help, thanks!

      - Andrew

      Delete
    2. OK, I do have a question that I can't seem to sort. I have a mobile site, and now photoswipe used via your method. The swipe works great, but the jquery.mobile-1.0rc2.min.css overwrites a bunch of the styles I have defined in the style sheet I have been working on. Doesn't seem to matter which order I attach the sheets in, nor if I put any !important rule next to the styles in that original style sheet.

      So, why is the jquery.mobile-1.0rc2.min.css overwriting my style sheet?

      Delete
    3. I can't say, but if nothing is overlapping (e.g. you don't have 2 different rules for "body" now) then perhaps JQuery Mobile's style sheet is only conflicting with your style sheet in a visual manner, such as limiting the width of your website to something smaller than it should be.

      I recommend removing your style sheet and adding in a few pieces at a time to make them work with JQM as well.

      - Andrew

      Delete
    4. I think I found a way thru. I got the unthemed file from jQuery Resources:
      link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.1/jquery.mobile-1.4.1.min.css" /

      Now I just have to style the gallery on the mobile page myself, and the photoswipe seems to work still!

      Delete
  27. Hi , I am much more interested in how to handle event's in photoswipe. Is it possible to do something like this:

    onImageLoad : do somthing


    I have been googling around without any good result.

    thanks.

    ReplyDelete
    Replies
    1. If you view the source code of the example page: $("#gallery a:first").click();

      You'll see this line of code (line 26):

      $("#gallery a:first").click();

      There, I used the JQuery click function to simulate a mouse click on a particular image (the first "a" tag in the "gallery" div). You could then use the JQuery load function just like in their first example here: http://api.jquery.com/load-event/

      (the "book" image example), and inside that function make a call like what I showed you above.

      - Andrew

      Delete
    2. Sorry, this* example page: http://thecodingwebsite.com/tutorials/photoswipe/photoswipe.html

      - Andrew

      Delete
    3. Hi Andrew, thanks for the reply. I understand what you did in the code you above. basically, what I would like to do is to assign a class to an element once photoswipe image is loaded and remove that class once its unloaded/closed.

      Delete
    4. That's beyond the scope of this tutorial. You'll have to look at Photoswipe's code or send them a message about it.

      - Andrew

      Delete
  28. Hi Andrew,

    I have added the $("#gallery a:first").click(); and it works fine to automatically go to the first image instead of thumbnail page.

    When it goes to the first image, it will stay there until we click on the play button. My question is how can I make the gallery automatically on "play" mode when people first land on that 1st image.

    Thanking in advance, Andrew.

    ReplyDelete
    Replies
    1. Try one of these solutions:

      http://stackoverflow.com/questions/10325304/want-to-add-autoplay-setting-to-responsive-image-gallery
      http://community.theturninggate.net/topic/666/autostarting-the-slideshow/

      - Andrew

      Delete
  29. I found this tutorial immensely helpful. Thank you very much for the effort. I have only one question: how can I make it such that the ESC key exits from the gallery view (as opposed to having to click on the (X) on the icon bar)?

    Rob Urban

    ReplyDelete
    Replies
    1. Glad it helped!

      It looks like that comes supported in the PhotoSwipe API: http://photoswipe.com/documentation/options.html

      Search for "escKey". Set that value to true.

      Alternatively it could probably be done with JavaScript, by detecting a key press event and checking if it's the Escape key: https://stackoverflow.com/a/3369743/1599699

      If you want to take this route for whatever reason, try the code in that particular answer I linked to there, and put it in a script tag in the head section of the page. Then instead of the alert in their code you can call the .close() method as seen here: http://photoswipe.com/documentation/api.html

      Delete