Create a filtered image gallery with jQuery and Fancybox

We are going to create a Fancybox image gallery that can be filtered by different categories using jQuery and Fancybox. If you have seen the
Isotope jQuery plugin, then you get the idea of what we will be talking about.

This the first part of a series of two tutorials.

filtered image gallery - Fig 01

 

Let's start by defining the two main sections we would need to focus on :

  • The categories selector (tab style)
  • The Fancybox image gallery (thumbnails collection)
The category selector

First, imagine our gallery organized by different categories, i.e. :

  • Animals
  • Landscapes
  • Architecture

The category selector will allow us to filter the gallery by any of the existing categories as above and browse it in Fancybox.

The basic html :

<div id="galleryTab">
  <a data-rel="all"  href="javascript:;" class="filter active">View all</a>
  <a data-rel="anim" href="javascript:;" class="filter">Animals</a>
  <a data-rel="land" href="javascript:;" class="filter">Landscapes</a>
  <a data-rel="arch" href="javascript:;" class="filter">Architecture</a>
</div>

Notice that we have set a (HTML5) data-rel attribute to each link to define the category they will be related to. Also notice that the value of each data-rel attribute corresponds to the first 4 letters of each category for convention purposes. Our initial state is "View all" (class="active").

The fancybox image gallery (thumbnails collection)

If you have ever used Fancybox, the html is pretty straight forward : wrap your image thumbnails with a link to a big version of each image.

<div class="galleryWrap">
  <a class="fancybox" data-fancybox-group="gallery" data-filter="anim" href="./animals/animal01.jpg"><img src="./thumbs/animal01.jpg" alt="" /></a>
  <a class="fancybox" data-fancybox-group="gallery" data-filter="anim" href="./animals/animal02.jpg"><img src="./thumbs/animal02.jpg" alt="" /></a>
  <a class="fancybox" data-fancybox-group="gallery" data-filter="land" href="./landscape/landscape01.jpg"><img src="./thumbs/landscape01.jpg" alt="" /></a>
  <a class="fancybox" data-fancybox-group="gallery" data-filter="land" href="./landscape/landscape02.jpg"><img src="./thumbs/landscape02.jpg" alt="" /></a>
  <a class="fancybox" data-fancybox-group="gallery" data-filter="arch" href="./architecture/architect01.jpg"><img src="./thumbs/architect01.jpg" alt="" /></a>
  <a class="fancybox" data-fancybox-group="gallery" data-filter="arch" href="./architecture/architect02.jpg"><img src="./thumbs/architect02.jpg" alt="" /></a>
  ... etc.
</div>

Notice that the initial value of the data-fancybox-group attribute has been set to "gallery". That will all allow us to browse all the images from all categories in Fancybox.

Also notice that each link has a data-filter attribute, where we can set what category this image will belong to.

HINT : you can add additional classes to your html code in order to apply custom CSS styles to the category selector tabs and the image thumbnails.
The Fancybox script

For our gallery, we will be using Fancybox v2. The script is very basic, just notice I have decided to use the Fancybox's buttons helper to navigate through the gallery though :

jQuery(function($){
    // fancybox
    $(".fancybox").fancybox({
        modal: true, // disable regular nav and close buttons
        // add buttons helper (requires buttons helper js and css files)
        helpers: {
            buttons: {}
        } 
    });
}); // ready
The category selector jQuery script

To filter the elements by category, the script will need to perform basically two things :

  • Show only those (thumbnail) elements that their data-filter attribute matches the data-rel attribute of the selected category tab.
  • Set the data-fancybox-group attribute to match the selected filter so only those elements will be shown in the Fancybox gallery.
jQuery(function ($) {
    // fancybox
    $(".fancybox").fancybox({
        modal: true, // disable regular nav and close buttons
        // add buttons helper (requires buttons helper js and css files)
        helpers: {
            buttons: {}
        } 
    });
    // filter selector
    $(".filter").on("click", function () {
        var $this = $(this);
        // if we click the active tab, do nothing
        if ( !$this.hasClass("active") ) {
            $(".filter").removeClass("active");
            $this.addClass("active"); // set the active tab
            // get the data-rel value from selected tab and set as filter
            var $filter = $this.data("rel"); 
            // if we select view all, return to initial settings and show all
            $filter == 'all' ? 
                $(".fancybox")
                .attr("data-fancybox-group", "gallery")
                .not(":visible")
                .fadeIn() 
            : // otherwise
                $(".fancybox")
                .fadeOut(0)
                .filter(function () {
                    // set data-filter value as the data-rel value of selected tab
                    return $(this).data("filter") == $filter; 
                })
                // set data-fancybox-group and show filtered elements
                .attr("data-fancybox-group", $filter)
                .fadeIn(1000); 
        } // if
    }); // on
}); // ready

And that's it. See it working.
 
DEMO

Use your CSS to style your selector tabs as well as your image thumbnails in your most creative way.

 
In Part 2, we will learn how to create our gallery from images stored in in different sub-directories and create their corresponding thumbnails automatically using php.

06. June 2013 by
Categories: code, fancybox 2, html5, jquery, plugins | 38 comments

  • Virginia

    This is really good! thank you!
    I was wondering if is there a way to aboid seeing all the thumbs when loading the page...? is there?
    Thank you! :)

    • JFK

      @Virginia : I think it's possible, but that is a customization no part of this tutorial that you may need to code yourself ;)

  • Bhoomi

    I have multiple sorting categories,
    data-filter="anim,land"
    but its not working.

    • JFK

      @disqus_0d5of64vlE:disqus
      The script is designed to handle a single data-filter You may need further customization to handle multiple filters.

      • mahendra patil

        hello bro....

        can jquery code run in notepad ?

        • JFK

          you can edit jQuery in notepad but not run it

  • Leslie Pfenninger

    Using XML to contain the gallery. I need multiple galleries on the same page. The XML loads correctly except for the location of the thumbnails in the galleries after the first. If the first gallery has 4 images, the second gallery will start loading thumbs in the fifth position and so on. Can you help place the thumbnails correctly? Here are the links: http://www.onamrecords.com/A&M_Ads_1960sTEST.html and http://www.onamrecords.com/britgallery.xml. Many thanks in advance.

    • JFK

      The code is freely available "as is". Individual customizations may need to be managed as separated projects ($). Thanks for your understanding.

  • aldi

    why my fancybox_button.css can't display

    • JFK

      I cannot tell. Check your paths and make sure your files are in the place you are trying to load them from.

  • geranbaha

    I've added the filtering, but it does not work, I think I am doing something wrong with the jquery

  • kahwei

    can i pass a to the data-filter? will it still work?

  • kahwei

    i mean i wud like to pass data from my query to the data-filter

    • JFK

      Have your tried? ;)

  • Pingback: Learn | Pearltrees()

  • Pingback: 20 Best jQuery Plugins from February 2015 | BytesWire()

  • Sarah Bennet Mills
    • JFK

      @sarahbennetmills:disqus : Thank you. I just want to clarify I am not FancyBox author. I just featured it in this post. All credits go to Jānis Skarnelis

  • Lucky

    Works fine, but i have a one question, How can i set to display images from my specyfic category by default at start, instead all images from all categories ??

    • JFK

      After you have loaded all your scrips, you could add

      $(".filter").eq(1).trigger("click")

      ... where the number you place inside .eq(1) is the sequential number of the filter you want to start the gallery with (bear in mind that `0` represents the first filter element)

      • Lucky

        That was easy - works fine, thx for help :)

        • Vinayak

          Hey can you tell more about the same.
          Thanks!

      • Jolas Parohinog

        in which part i will put that code?

  • Pawel

    I added this gallery to my website and on local server / hard drive it's works great ! But when I upload it to web server it doesn't work. I copied code from your DEMO, links too and still doesn't work. Can you help me and tell me what can be wrong ?

    • JFK

      Many things can be wrong but first thing I would check is paths (to jQuery/fancybox/images) and file names (image01.jpg and image01.JPG might be considered two different files by the web server) Please bear in mind that this post can be used as a reference "as is", any customization or individual technical support may be subject to a separated fee (thanks for your understanding)

  • Jan Staes

    I'm making a website and use this css3 Lightbox http://tympanus.net/codrops/2011/12/26/css3-lightbox But the thing is that it doesn't have a filter. This "filter effect" you made would be perfect. I want to keep the css3 Lightbox but want to add your filter effect to it. Is this possible? I'm not really good at coding, so I hope its not to difficult.

    • JFK

      I think it's possible since the filter in my code is completely independent from the lightbox code.

  • Matt

    Hi, i've added it to my website and it's working. I'm trying to get rid of the feature which shows the image in large when clicked. How would i remove this? I've been messing around with the fancybox.js but cannot remove it without breaking the other part of the code.

    • JFK

      just remove the fancybox initialization code
      $(".fancybox").fancybox({ ...})

  • Jonas

    Hey man, thanks for the great guide. I'm trying to get multiple data-filters, for example: anim and land. (data-filter="anim land")
    Any idea how I can use both?

  • raj mohammed

    Works fine, but i have a one question, How can i add title or content for large image showing in slideshow

    • Bola Raafat

      title="XxX"

  • anika

    how to remove view all

  • Allison Cairns

    I love it...works great! :)
    Is there a way to center the images when in mobile view? They are all aligned but towards the left hand side. It looks perfect on desktop but just trying to tweak mobile view!

    • Bola Raafat

      use media query (resposive web page)

  • Bola Raafat

    excuse me what if i dont want to remove the other categories and i just want to decrease the opacity of them i used Fade to() function instead of fade out() but it didn't work
    so please how can i do it ?

  • Francisco Braz

    How do I start with any filter? For example anim

  • Naseeb Dangi

    How do i create sub filter. suppose i have a filter tab name programs and i need to add sports and dance filter tabs inside programs tabs so i can view dance and sports photos separately