jQuery

Creating a “Filterable” Portfolio with jQuery

Tutorial Details
  • Technology: jQuery, CSS
  • Difficulty: Intermediate
  • Completion Time: 1-2 hours

If you have worked in your field for a while, there is a pretty good chance that you have a rather extensive portfolio. To make it a little easier to navigate, you will probably be tempted to break them into different categories. In this tutorial, I will show you how to make “filtering by category” a little more interesting with just a little bit of jQuery.

Final Product

1. The Markup

Our portfolio is nothing more than a simple unordered list:

<ul id="portfolio">
	<li><a href="#"><img src="images/a-list-apart.png" alt="" height="115" width="200" />A List Apart</a></li>
	<li><a href="#"><img src="images/apple.png" alt="" height="115" width="200" />Apple</a></li>
	<li><a href="#"><img src="images/cnn.png" alt="" height="115" width="200" />CNN</a></li>
	<li><a href="#"><img src="images/digg.png" alt="" height="115" width="200" />Digg</a></li>
	<li><a href="#"><img src="images/espn.png" alt="" height="115" width="200" />ESPN</a></li>
	<li><a href="#"><img src="images/facebook.png" alt="" height="115" width="200" />Facebook</a></li>
	<li><a href="#"><img src="images/google.png" alt="" height="115" width="200" />Google</a></li>
	<li><a href="#"><img src="images/netflix.png" alt="" height="115" width="200" />Netflix</a></li>
	<li><a href="#"><img src="images/nettuts.png" alt="" height="115" width="200" />NETTUTS</a></li>
	<li><a href="#"><img src="images/twitter.png" alt="" height="115" width="200" />Twitter</a></li>
	<li><a href="#"><img src="images/white-house.png" alt="" height="115" width="200" />White House</a></li>
	<li><a href="#"><img src="images/youtube.png" alt="" height="115" width="200" />YouTube</a></li>
</ul>

Note: I was by no means a part of creating these wonderful sites; I am just using them as examples.


2. Categorizing the Portfolio

We are going to assume that our portfolio can be broken down into 5 categories:

  • Design
  • Development
  • CMS
  • Integration
  • Information Architecture

In order to use the categories we have defined, we will convert them to lowercase and replace all spaces with hyphens:

  • Design = design
  • Development = development
  • CMS = cms
  • Integration = integration
  • Information Architecture = information-architecture

We are going to assume that each portfolio item could be in one or many categories, so we are going to randomly add our newly created categories as classes to the list items:

<ul id="portfolio">
	<li class="cms integration">
		<a href="#"><img src="images/a-list-apart.png" alt="" height="115" width="200" />A List Apart</a>
	</li>
	<li class="integration design">
		<a href="#"><img src="images/apple.png" alt="" height="115" width="200" />Apple</a>
	</li>
	<li class="design development">
		<a href="#"><img src="images/cnn.png" alt="" height="115" width="200" />CNN</a>
	</li>
	<li class="cms">
		<a href="#"><img src="images/digg.png" alt="" height="115" width="200" />Digg</a>
	</li>
	<li class="design cms integration">
		<a href="#"><img src="images/espn.png" alt="" height="115" width="200" />ESPN</a>
	</li>
	<li class="design integration">
		<a href="#"><img src="images/facebook.png" alt="" height="115" width="200" />Facebook</a>
	</li>
	<li class="cms information-architecture">
		<a href="#"><img src="images/google.png" alt="" height="115" width="200" />Google</a>
	</li>
	<li class="integration development">
		<a href="#"><img src="images/netflix.png" alt="" height="115" width="200" />Netflix</a>
	</li>
	<li class="information-architecture">
		<a href="#"><img src="images/nettuts.png" alt="" height="115" width="200" />NETTUTS</a>
	</li>
	<li class="design information-architecture cms">
		<a href="#"><img src="images/twitter.png" alt="" height="115" width="200" />Twitter</a>
	</li>
	<li class="development">
		<a href="#"><img src="images/white-house.png" alt="" height="115" width="200" />White House</a>
	</li>
	<li class="cms design">
		<a href="#"><img src="images/youtube.png" alt="" height="115" width="200" />YouTube</a>
	</li>
</ul>

Adding Category Navigation

Now that we have the portfolio pieces in place, we are going to need some way to navigate through them. Another unordered list should do:

<ul id="filter">
	<li class="current"><a href="#">All</a></li>
	<li><a href="#">Design</a></li>
	<li><a href="#">Development</a></li>
	<li><a href="#">CMS</a></li>
	<li><a href="#">Integration</a></li>
	<li><a href="#">Information Architecture</a></li>
</ul>

Since I want the default view of the portfolio to show All items, I have assigned a class of current to the first list item.

You will probably look at that and question me on the accessibility of this example. My thought is that you have 3 options to solve that problem.

  1. When creating a portfolio like this, there is a strong probability that it will be database driven. Thus, you should be able to create a separate page for each category. So if a user does not have JavaScript enabled, they can go to the separate page with the filtered portfolio.
  2. You can use a similar technique from my last tutorial: setting a parameter in the url.
  3. You could always just write in the navigation with JavaScript before the portfolio items:
    $(document).ready(function() {
    	$('ul#portfolio').before('<ul id="filter"><li class="current"><a href="#">All</a></li><li><a href="#">Design</a></li><li><a href="#">Development</a></li><li><a href="#">CMS</a></li><li><a href="#">Integration</a></li><li><a href="#">Information Architecture</a></li></ul>');
    });

Ok, you’ve got my notes on accessibility, so don’t criticize me for not thinking about it.


3. The CSS

This tutorial is not meant to be about CSS, so I’m going to run through the CSS pretty quickly.

I always start with some basic styles as a sort-of framework, so I’m not going to go over those styles right now. These styles basically just act as a reset and define some styling for basic elements.

To start, I just want to display the categories across the top horizontally with a border between each:

ul#filter {
	float: left;
	font-size: 16px;
	list-style: none;
	margin-left: 0;
	width: 100%;
}
ul#filter li {
	border-right: 1px solid #dedede;
	float: left;
	line-height: 16px;
	margin-right: 10px;
	padding-right: 10px;
}

Next, I want to remove the border from the last list item (in browsers that support it) and change the display of the links:

ul#filter li:last-child { border-right: none; margin-right: 0; padding-right: 0; }
ul#filter a { color: #999; text-decoration: none; }

I also want to make sure and differentiate the currently selected category:

ul#filter li.current a, ul#filter a:hover { text-decoration: underline; }
ul#filter li.current a { color: #333; font-weight: bold; }

Ok, now that we have the category navigation styled, let’s focus on the actual layout of the portfolio. Let’s plan on floating 3 list items next to each other with a border around each one:

ul#portfolio {
	float: left;
	list-style: none;
	margin-left: 0;
	width: 672px;
}
ul#portfolio li {
	border: 1px solid #dedede;
	float: left;
	margin: 0 10px 10px 0;
	padding: 5px;
	width: 202px;
}

Now, we just need to add some basic styling for the images and links:

ul#portfolio a { display: block; width: 100%; }
ul#portfolio a:hover { text-decoration: none; }
ul#portfolio img { border: 1px solid #dedede; display: block; padding-bottom: 5px; }

Compensating for Internet Explorer 6

Of course, let’t not forget about our friend IE6. Once you start clicking through some of the filters, the layout gets a little crazy.

IE Screenshot

From what I can tell, it is the dreaded IE Double Margin bug. I tried applying display: inline to the list items once they are filtered, but that didn’t seem to fix it. So my best solution was to just halve the right margin:

ul#portfolio li { margin-right: 5px; }

We are of course only going to serve this IE6 specific stylesheet using conditional comments:

<!--[if lt IE 7]>
<link href="stylesheets/screen-ie6.css" type="text/css" rel="stylesheet" media="screen,projection" />
<![endif]-->

Yeah, it doesn’t look as good, but you know what: I don’t care. If you are using IE6, you deserve it.


4. The jQuery

Ok, now that we have the markup and CSS all done, let’t get to the important part of this tutorial: the JavaScript.

We are going to start by including the latest version of jQuery in the head of our document.

<script type="text/javascript" src="scripts/jquery.js"></script>

Next, we want to execute our code once the document is loaded.

$(document).ready(function() {

});

Now, we don’t want to do anything until one of our categories is clicked. We also want to make sure that we do not follow the href value of the link, so we need to return false:

$('ul#filter a').click(function() {
	return false;
});

Once a category link is clicked, I want to do a couple of things: remove the outline on the clicked link, remove the class of current on the list item that has it, and add the class of current on the parent of the clicked link:

$(this).css('outline','none');
$('ul#filter .current').removeClass('current');
$(this).parent().addClass('current');

Next, we want to get the text inside of the clicked link, convert it to lowercase, and replace any spaces with hyphens (just like before when we were creating the category classes):

var filterVal = $(this).text().toLowerCase().replace(' ','-');

The first case of the script is when the All link is clicked. When that is clicked, we want to show all of the portfolio items and remove the class of hidden:

if(filterVal == 'all') {
	$('ul#portfolio li.hidden').fadeIn('slow').removeClass('hidden');
}

Otherwise, one of the actual categories were clicked. So we want to go through each portfolio item and check to see if it has the class that equals the value of the category clicked. If it does not have the class, we want to fade out the list item and add a class of hidden. It it does have the class, we want to fade it in and remove the class of hidden:

else {
	$('ul#portfolio li').each(function() {
		if(!$(this).hasClass(filterVal)) {
			$(this).fadeOut('normal').addClass('hidden');
		} else {
			$(this).fadeIn('slow').removeClass('hidden');
		}
	});
}

The Finished Script

Let’s take a look at the entire script:

$(document).ready(function() {
	$('ul#filter a').click(function() {
		$(this).css('outline','none');
		$('ul#filter .current').removeClass('current');
		$(this).parent().addClass('current');

		var filterVal = $(this).text().toLowerCase().replace(' ','-');

		if(filterVal == 'all') {
			$('ul#portfolio li.hidden').fadeIn('slow').removeClass('hidden');
		} else {
			$('ul#portfolio li').each(function() {
				if(!$(this).hasClass(filterVal)) {
					$(this).fadeOut('normal').addClass('hidden');
				} else {
					$(this).fadeIn('slow').removeClass('hidden');
				}
			});
		}

		return false;
	});
});

Some people may not like the effect, but I think it looks pretty cool how they all kind of dance around. This is definitely not the only way to accomplish something like this, and it could easily be built on to do other things.

This technique is actually evolved from the coding that I did for my company’s portfolio.

Final Product

5. One Quick Note

You may have noticed that I was adding and removing the class of hidden on the items as I was toggling the visibility. While I didn’t end up doing anything with the class, I try and make it a habit to add and remove classes to denote the state they are in. You may not use it immediately, but it can provide a hook for you do stuff with in the future.

  • Subscribe to the NETTUTS RSS Feed for more daily web development tuts and articles.


Add Comment

Discussion 262 Comments

Comment Page 5 of 5 1 ... 3 4 5
  1. mainframezen says:

    kudos

    ( duplicate comment)
    The ‘-’ replace does not support more than two words.

    Used this line instead:

    var filterVal = $(this).text().toLowerCase().replace(/ /g,’-');

  2. Jay says:

    Is there a way to make the filtering a smooth animation? I like this technique, but jQuery Quicksand looks so much better.

    Can there be a slide animation for the items that do not fade?

  3. Nathan says:

    Hi, Great script but how do I change it to show nothing in the portfolio unless a cateogrie is selected.

    I’ve removed “current” but now joy.

  4. Ryan says:

    Hey,

    I was wondering if it is possible to have the filter modifiers at the top being icons instead of text? I have the icons in place, but I do not know how to reference them later in the class tag, as they have no text? I tried using the alt text tag text but that did not work

  5. Andy says:

    I agree with Jay – Is there a way to make the filtering a smooth animation? Perhaps using jQuery Easing plugin? I’m not sure how this would be done. Any suggestions?

  6. is there anyway this can be applied to a single DIV instead of list items? i’ve tried but not getting the result im looking for?

  7. This is a really interesting way to “compress” the script. I was using one class and one condition for each elements of the li… I’ll get a try to this now. Thank you

  8. Amigo says:

    Please support diacritics? ˇ ´ etc.
    THX

  9. Jon Edwards says:

    I’d like to add a line of jquery that checks for every third child after the filter has run, and adds a class “.last” to it. Currently, I’m using this to remove the right margin from every third li (each row has 3 li’s)…

    $(‘ul#portfolio li:nth-child(3n)’).addClass(‘last’);

    This works jquery will work standalone before the filter runs, but I want it to work after the filter as well… Any suggestions would be appreciated.

    • mae5tr0 says:

      This works great

      $(‘ul#filter a’).click(function() {
      $(“ul#portfolio”).find(“li”).removeClass(“last”);
      });

      $(‘ul#filter a’).click(function() {
      $(‘ul#portfolio li.visible’).each(function(i) {
      i=(i+1);
      if(i%3==0){
      $(this).addClass(“last”);
      }
      });
      });

  10. Noah says:

    Thanks for the wonderful script. I was wondering if the community could help me with a conundrum, I have a mobile site that I’m attempting to get this working on, but haven’t had any luck. You can view the site at http://www.mpwrks.com/index.php/ipad_index_previews.

    When one of the filter icons is pressed, all of the portfolio items disappear and fail to reappear? I’m using the standard framework.js setup.

    Any assistance would be greatly, greatly appreciated!!

  11. Adrian says:

    This is a great script. We did something like this on our company’s portfolio page, except each item had to be in its own div. We gave them classes to sort. Then we used the id’s to create onclick overlays. And we kept all our css on our main style.css file.

    The resulting code for each element is simply

    Company Name

    You can see how it works at http://orangesparrow.com/our-work.html

  12. Ross says:

    Love this…I’m using the effect to just “dim” non-matched elements in a portfolio setting. But…I have a new project that is looking for something just slightly more sophisticated.

    Basically, we’ll have a number of items that are assigned to various categories and we need a way to filter based on more than one category at a time. So, in this example, instead of just selecting just “CMS” we’d need to be able to select “CMS” and “Design”.

    Anyone have any thoughts on a way to customize/implement? Thanks in advance.

  13. You can just add -webkit-transition: all .3s linear; in the css, if you want to have the position changes smooth.

  14. ARyan says:

    i dont want to show dafult all than what to do
    please help meeeeeeeeeee

  15. fra says:

    Very nice, just May I use it with Ligthbox too?thanks, bye

  16. venkatsh says:

    I am ui developer ( css,XHTML,jquery) & Designing ( adobe photoshop, corldrow,Indesign creating templates & logos ext….)

    I haveing 4years of exp

    I am looking of freelance works

    This is my mobile No 919963582997

    Thanks

  17. Aravind says:

    Thanks for the nice stuff….

  18. Pedro Cardoso says:

    Hi, i’m trying to create a link from an external page to a category in my portfolio page. How can i do that?

    I’ve tried to use anchors on a category and link to the anchor from other pages, but it shows all the items when it was supposed to show only the items of that category.

    Anybody knows how to solve this?

    Thanks. Any help would be great.

  19. Dennis says:

    I only want to let some greetings here. I done every step of ur tutorial and it workt like out of the box. Thx a lot for ur work.

    Dennis

  20. Gino Hucks says:

    I have been surfing on-line greater than three hours today, yet I never found any attention-grabbing article like yours. It’s pretty worth sufficient for me. In my opinion, if all website owners and bloggers made excellent content material as you probably did, the net might be much more useful than ever before.

  21. ktsixit says:

    I finally found a solution to the external link issue. You can view the solution here:
    http://savethefix.wordpress.com/2011/12/06/filterable-portfolio-with-jquery-with-external-link-support/.

  22. tutspress says:

    Awesome tutorial thanks!

  23. Great tutorial. Really great way to make a simple and clean layout.

  24. pingram3541 says:

    Great tutorial. I struggled with other “plugins” like quicksand working with jquery masonary and was able to get this working…except that the hidden elements retain their space in the page.

    It would be nice if I could get it to work like the demo where the ‘filtered’ results re-align within the container left-to-right, top-to-bottom but I haven’t figured this out yet.

  25. Anjieya says:

    Could we make different color for the selected cursor?
    Because i only saw the link become no under line after selected cursor.
    awesome work.
    thanks you

  26. Bernard says:

    Thanks! It works great.

  27. Asad says:

    Is it possible to implement a double filter? For example, if I wanted to display items that only belonged to both “Design” AND “Integration”. I very much need this functionality for my website and would like to know how difficult it would be to implement. Thank you for any information!

    - Asad

  28. alek says:

    ive made some changes to avoid jumping objects on menu selection change

    ===============================================================
    $(document).ready(function() {
    $(‘ul#filter a’).click(function() {
    $(this).css(‘outline’,'none’);
    var filterVal = $(this).text().toLowerCase().replace(‘ ‘,’-');
    var itemsLength = $(‘ul#portfolio li:visible’).length;
    $(‘ul#portfolio li:visible’).each(function(i) {
    $(this).fadeOut(‘slow’, function(){if(itemsLength == ++i){show(filterVal);}});
    });
    return false;
    });

    });
    function show(filterVal){
    if(filterVal == ‘all’) {
    $(‘ul#portfolio li’).fadeIn(‘slow’);
    } else {
    $(‘ul#portfolio li’).each(function() {
    if($(this).hasClass(filterVal)) {
    $(this).fadeIn(‘slow’);
    }
    });
    }
    }
    =================================================================
    * ive removed additional styles
    * added time out then the last item will be faded out
    * hide all the items before removin some of them and fade in only those that must be showen

  29. Patrick says:

    This is amazing, thank you very much.

    It helped me a lot with getting a filterable portfolio!

  30. Hugo Froes says:

    Hi guys, this is an incredible script, i’ve even used it for my bookmarks on my computer. I’m now trying to apply this on a site, but I’m having 2 problems.

    1. Instead of a menu, I wanted to use a dropdown (form list) to filter the images.

    2. I’m using a nth:child to take away the margin in every third , is there a way to add this function after the filter has run? My code is as follows:

    $(document).ready(function() {
    $(‘ul.filter a’).click(function() {
    $(this).css(‘outline’,'none’);
    $(‘ul.filter .current’).removeClass(‘current’);
    $(this).parent().addClass(‘current’);

    var filterVal = $(this).text().toLowerCase().replace(‘ ‘,’-');

    if(filterVal == ‘todos’) {
    $(‘ul.promos_gerais li.hidden’).fadeIn(‘slow’).removeClass(‘hidden’);
    } else {

    $(‘ul.promos_gerais li’).each(function() {
    if(!$(this).hasClass(filterVal)) {
    $(this).fadeOut(‘normal’).addClass(‘hidden’);
    } else {
    $(this).fadeIn(‘slow’).removeClass(‘hidden’);
    }
    });
    }

    return false;

    });
    });
    jQuery(‘.promos_gerais li:nth-child(3n+3)’).css({ marginRight: ’0px’ });

  31. Jer says:

    I got this script working it’s great. I’ve very new to developing.

    How do I get on specific category to load when the page loads rather than all.

    I’d simply like it to either display nothing until button click or display on filtered catagory

  32. Soumil says:

    Hi, I’d really like to add this to my tumblr account. Is there any tutorial available on NetTuts on how to add this or any Jquery plugin/code in tumblr?

  33. thanks for the post i liked it soo much and it was very useful but i have a question why doesn’t the custom field panel isn’t showing in the portfolio page in the admin panel can u please help me

  34. Hello,
    It’s a great idea, but i have a problem.
    I have a slider calling “http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js”, what i have to do to not conflict with the “scripts/jquery.js”?

Comment Page 5 of 5 1 ... 3 4 5

Add a Comment

To add a code snippet to your comment, please wrap your code like so: <pre name="code" class="html">YOUR CODE</pre>. You can replace the class name with "js," "css," "sql," or "php." If there are any "<" or ">" within your code, please search and replace them with: &lt; and &gt; respectively.