Tutorial: Dynamic slideshow with PHP & JQuery 101

When I set out to add database driven player info at NuggetsHoops.com, I knew that I wanted to include code that would display some of the many images that I had set aside for each NBA player. I also knew that I would continue to add new pictures. Application code that could easily display old and new images, without additional effort for each added image would work best.

I had already written PHP code that could look at a folder and create a list of images to be displayed. When I ran across the powerful jQuery Cycle Plugin, I had found a great way to display them.

Let’s get coding. This tutorial depends on PHP 5, jQuery 1.2.3 or later, jQuery Cycle Plugin version 2.51 or later.

Add the following Javascript to your PHP/HTML to enable and call the Cycle Plugin:



Note that there are many options and styles of animation provided by the powerful Cycle plugin.

Add the following PHP to iterate over any folder and dynamically generate img tags using any images found in the folder:
$directory = 'images/players/' . $row['imageName'];
try {
// Styling for images
echo "

";
foreach ( new DirectoryIterator("../" . $directory) as $item ) {
if ($item->isFile()) {
$path = "/" . $directory . "/" . $item;
echo "";
}
}
echo "

";
}
catch(Exception $e) {
echo 'No images found for this player.
';
}

Any img tags within an HTML element of class ‘myslides’ (or whatever you initialized the Cycle plugin with in the Javascript) will have the slideshow behavior added to it. The $row array on line 1 is referencing a database query result, but could be set in a number of ways for your specific needs. The DirectoryIterator reference on line 5 is a builtin class in PHP5.

Here’s the CSS to style the images being displayed in the slideshow:

#myslides {
width: 340px;
float: right;
padding: 0;
margin: 0 auto;
margin-top: 20px;
}

#myslides img {
padding: 10px;
border: 1px solid rgb(100,100,100);
background-color: rgb(230,230,230);
width: 320px;
top: 0;
left: 0
}

So, there’s a very quick walk thru a working example to generate a dynamic slideshow from any folder of images. If you’d like a full download of the code, or any further explanation, please leave a comment!

You can see this code in action by just clicking on any player’s name at the NuggetsHoops.com Roster page.

New – download the code for this Tutorial

[download#WithImage id=”1″]

Demo

101 thoughts on “Tutorial: Dynamic slideshow with PHP & JQuery

  1. Reply Ssemwanga May 18,2011 4:12 AM

    when i do as you demonstrated i got no error but again there no image playing so what can i do

    • Reply alan May 18,2011 10:12 AM

      Ssemwanga – is this your first comment here? You make it sound as if you have tried this tutorial more than once with no success.

      Do you see the message “No images found for this player” on the page where you are trying to create the slideshow? Do you see other text on the page (that you wrote) or is it blank?
      Do you have access to your server logs?

      Another idea is to try adding a small snippet of PHP code *after* where you are attempting to display the slideshow. In this way, you can see if the slideshow is causing an error in PHP where it won’t continue to process PHP code on your page.

      Just add something like this < ?php echo "Made it here!" ?>

  2. Reply Lorrie Gilboy Jun 2,2011 6:35 PM

    Hey, I really don’t think saying this on your post Tutorial: Dynamic slideshow with PHP & JQuery would be the appropriate place but I couldn’t locate a contact page form within your somewhat messy theme (sorry). My readers would always tell me exactly the same thing so I switched over to a new theme from http://tinyurl.com/themeforestz. I’ve only gotten kind comments after. Regards, Lorrie Gilboy

  3. Reply Iomoio Jun 5,2011 5:19 AM

    I know this is really boring and you are skipping to the next comment, but I just wanted to throw you a big thanks – you cleared up some things for me!

  4. Reply Tamika Hunstiger Jun 12,2011 9:37 PM

    good blog man, I really admire your writing style that you are using for your posts and stuff, really hollywood…

  5. Reply gare Jun 16,2011 8:36 AM

    Hi Alan,

    Thanks for the clearly written demo. To be honest, the download package is a total winner! An entire working example to reverse engineer!

    Awesome.

    Keep up the great work. I’ll look around your site briefly to click on some ads, if you have any. 🙂

    gare

  6. Reply William Rouse Jun 16,2011 7:32 PM

    It would be nice to add a Next and Back button. How would you do this?

    • Reply alan Jun 16,2011 11:29 PM

      William – I think that would be doable. I’ll take a crack at adding that and adding it as a configuration option. I’ll update the tutorial and the download if I can work it out in the next week or so, and add a comment. Check back in a few!

  7. Reply William Rouse Jun 21,2011 7:03 PM

    Thanks for looking into it Alan.
    WBR

  8. Reply طراحی سایت Jul 24,2011 2:49 AM

    please put slideshows that independence from languages

  9. Reply Stray Aug 25,2011 4:59 PM

    This is great. Thank you! I’ve been trying to make a JQuery/PHP slideshow work for one of my clients and this tutorial is so clear and useful. Working wonderfully.

  10. Reply Renu Nov 22,2011 12:57 PM

    Hi Allan

    I went through the tutorial and its a real help for someone whose new to php and jquery too. I wanted a help regarding the slideshow content. Is there any way through which we can also add content for the slideshow as per the image. I appreciate any quick response from your side.

    Thanks in advance.

    Renu.

    • Reply alan Nov 22,2011 1:20 PM

      Renu – are you asking about having text or html associated with each image in the slideshow? If so, yes… have definitely thought about that for my own use. I haven’t come up with a clean solution that wouldn’t take away from the easy way of adding new content that I have in place right now though. One thought would be to have the slideshow code look for a file like “descriptions.txt” that it could parse and add descriptions/captions for any matching filenames in that file. If it didn’t find one, it would still just show the image as it does today. If that sounds good I’ll add that to my future features for this tutorial and post an update in a future version.

  11. Reply san Feb 22,2012 3:29 AM

    Hello alan,

    After the end of the slideshow, i don’t want to see the border without picture. Please can you help me how to add line of code to keep the images in the loop.>?

    Thank you

  12. Pingback: What is the easiest way to put a photo gallery into an existing website? » free icons download

  13. Reply Daan Apr 25,2012 9:44 AM

    hello alan,
    i got the scriptt but i see all the pictures but they are under each other.
    can you help me?

    • Reply alan Apr 25,2012 1:37 PM

      Can you tell me what browser (FF, IE, Chrome) and version you are seeing the issue in?

      Also, if it’s possible, please share a link to the page where you are trying to use the slideshow.

  14. Reply subimal Jun 20,2012 9:43 AM

    Kindly tell me how to choose the images randomly from the folder for the slide show

  15. Pingback: 开发者经常用到的75 个功能强大的 jQuery插件和教程汇总(上篇) - TNM博客 - 知其然知其所以然 | 做而且还要做好 | 知足常乐

  16. Pingback: 开发者经常用到的75 个功能强大的 jQuery插件和教程汇总(上篇) | 编程·早晨

  17. Reply Survi Jan 3,2013 11:11 PM

    How can i use it in wordpress?Please suggest me something to include slides view dynmically for wordpress.

  18. Reply sam Jan 12,2013 2:40 AM

    Great tutorial, workes like a charm.
    ONe thing though: I can’t figure out what determines the order of the images from the imagefolder… It seems random now, or based on filesize or so, but I’d like the slideshow to display them alphabetically… Should probably use a sort command in the php code, but how?? all help welcome

    • Reply alan Jan 14,2013 4:52 AM

      A few changes are needed in the PHP code to provide an alphabetical sort.

      Replace lines 5-10 (see above in the PHP code snippet) with the following, and you should have what you are looking for:

      $itr = new SortingIterator( new FilesystemIterator($directory), ‘strnatcasecmp’);
      foreach ($itr as $myfile) {
      if ($myfile->isFile()) {
      //echo $myfile->getPathname() . PHP_EOL;
      $path = $directory . “/” . $myfile->getFilename();
      echo “<img src=\”” . $path . “\” />”;
      }
      }

      Then add the following snippet somewhere above, just below the start of the PHP tag.

      class SortingIterator extends ArrayIterator
      {
      public function __construct(Traversable $iterator, $callback)
      {
      if ( ! is_callable($callback)) {
      throw new InvalidArgumentException(sprintf(‘Callback must be callable (%s given).’, $callback));
      }

      parent::__construct(iterator_to_array($iterator));
      $this->uasort($callback);
      }
      }

      I will try to package this up better in a new download when I have more time.

  19. Reply sam Jan 13,2013 2:36 PM

    okay,
    With all my basic knowledge I rewrote the php part to using an array that I can sort. The array than gets printed, and yields the exact same results as the previous scripts, so a div with image tags, the PROBLEM:
    the image tags are not picked up by the js script… why not, all image tags should be picked up right?

    hoping for help here
    as a reminder, the initials problem is that I want the slide show to be alphabetically..

    Thanks, best Sam

    • Reply alan Jan 14,2013 5:00 AM

      Sam,

      All images are picked up by the javascript as long as they are contained in an element that matches the selector in the call to cycle().

      In my download, I created a div with the id of “myslides” and had the selector look for that with this code:

      $(‘#myslides’).cycle({
      fit: 1, pause: 2
      });

      Hope that helps!

  20. Reply uberdood Jan 22,2013 7:00 PM

    Do you have a working version with back/forward buttons yet?

  21. Reply Gaby Apr 4,2013 9:06 AM

    Hello, I first want to say how amazing you are. Thank you thank you thank you for posting this. I’ve been trying to find a way to make this possible. ANYWAY, I have a HUGE image folder, and I want to only show the 10 most current images(the camera is connected to an ftp server that automatically takes pictures every hour and uploads it to the folder). Is there a way to tweak the code for that?

    • Reply alan Apr 5,2013 11:36 PM

      Hi Gaby,

      Thanks for the kind words.

      This is un-tested, but here’s what I would do to modify the PHP code to grab the 10 latest images in a folder: (replacement of lines 5-10 in the PHP code above)

      $images = array();
      foreach (scandir($directory) as $node) {
      $nodePath = $directory . DIRECTORY_SEPARATOR . $node;
      if (is_dir($nodePath)) continue;
      $images[$nodePath] = filemtime($nodePath);
      }
      arsort($images)
      $newest = array_slice($images, 0, 10);

      Then you can just iterate over the array:

      foreach ($newest as $imageFile) {
      $path = “/” . $directory . “/” . $imageFile;
      echo ““;
      }

  22. Reply fred Apr 4,2013 8:11 PM

    doesnt seem to work

    • Reply alan Apr 5,2013 11:44 PM

      Fred,

      Other people have had success with it here. Can you share a few more details so that I can try and help? What browser are you using? Do you see any errors in the console of your browser when you view your test page? Try adding the Firebug plugin to Firefox for debugging purposes – it is very helpful.

  23. Pingback: 开发者经常用到的75 个功能强大的 jQuery插件和教程汇总(上篇) | news snack

  24. Reply Alexander Jul 10,2013 2:35 PM

    How do i center the slideshow?
    So it doesn’t matter how big the image is, every image is perfectly in the middle of the webpage.

  25. Reply eazybuzy Jul 20,2013 12:01 AM

    Hello,

    Thanks for the good work.

    I used to it and it worked on localhost, but once i am online it doesnt work anymore. it displays perfectly while i am online but when internet access is enabled, it just displays all the pictures below each other and it doesnt change.

    please help with any idea as to how to go about this.

  26. Reply eazybuzy Jul 20,2013 5:26 PM

    Thanks Alan , I have been able to resolve the issue, the reported error was

    Uncaught TypeError: Object [object Object] has no method ‘cycle’

    so i modified the script to

    $(document).ready(function(){
    $.getScript(‘/js/jquery.cycle.all.min.js’, function(){
    $(‘#myslides’).cycle({ fit: 1, pause: 2 });
    });
    });

  27. Reply Ashish Solanki Oct 7,2013 12:31 AM

    It really helps thank you

  28. Reply imran ali Dec 7,2013 2:45 AM

    hey frnds i am new here tell me how create flexible slider in php and jquery use and how use .htaccess file in php

  29. Reply jocelin Louis Feb 6,2014 5:47 AM

    Hi guys,can you please help?how can i add url to these images so that each image point to a new page?

  30. Reply leonardito Dec 4,2014 4:46 PM

    How can I incorporate this code in responsive design using DIV.
    Thanks for reply and Greetings.

  31. Reply Paddy H Dec 21,2014 5:46 PM

    Thanks this worked great for me. very simple and easy to understand…
    Just one question is there a way to speed up the translations between slides

  32. Reply Patrick Hughes Feb 5,2015 7:49 AM

    Hi Alan

    Great tutorial and great bit of code it works perfectly thank you very much for this. I searched long and hard to find a way of displaying a slide show of pictures without knowing the pictures names beforehand and encoding them into HTML. Anywhere I went looking for help said it could not be done but then I found your post and it’s perfect.

    Just 2 questions

    Q1. How can I increase the size of the picture box display in your code.

    Q2. Can this code be adapted to play video form a folder local on the server? Once again I have been told on different forms that the only way is by knowing the video name beforehand and encoding it into the player.

    (Example:

    Your browser does not support the video tag.
    )

    The issue is I work in a school and at the front door I have a screen that displays a local run website I am using your picture slider to display pictures and teachers just upload the images to a folder and it all done for them and displayed on the screen.

    My issue is if a teacher wants to display a video they need to deleat the last video that was played on the screen and rename the new video so that my HTML code will display the video on the screen so if there is a way of changing you code to play videos like it dose pictures so the teachers just need to drop in the videos into a local folder that would be great.

    Thanks

  33. Reply jason hirsh Feb 12,2015 11:08 AM

    This is really useful as a real novice in Jquery and PHP. The ability to load a slide show from a file has really streamlined some of my photo web page work… A demo or guide on how to incorporate slide controls would be REALLY great I got half way there borrowing code but not quite there

  34. Reply ryan Feb 18,2015 3:36 PM

    How can I make it pause longer between slides?

  35. Reply Paddy H Sep 13,2015 10:56 AM

    Hi Alan

    Thanks for the code it works great.
    I know the post is old just home your monitoring the replys still
    Is there any way this can be edited to play html5 videos from a folder and not a a picture slideshow

  36. Reply Kev Oct 8,2015 9:19 AM

    Hey I wonder if its possible to make this only look for jpgs in the image folder, I have the problem where .DS_Store files are automatically created any time I open the image folder and the script then tries to display this file as an image, any way to exclude?

Leave a Reply to Iomoio Cancel reply

%d bloggers like this: