Quick and Easy Filtering with jQuery

Quick and Easy Filtering with jQuery

Sep 24th in Screencasts by Jeffrey Way

In this week's screencast, we'll learn how to implement quick and dirty filtering without a database. By applying some classes and a touch of jQuery, we can implement a nice little system very quickly.

PG

Author: Jeffrey Way

Hi, I'm Jeff. I'm the editor of Nettuts+, and the Site Manager of Theme Forest. I spend too much time in front of the computer and find myself telling my fiance', "We'll go in 5 minutes!" far too often. I just can't go out to dinner while I'm still producing FireBug errors...drives me crazy. During my free time, I sporadically write articles for my own personal blog. If it will keep you in the good graces of the church, follow us on Twitter.

Overview

Just yesterday, I was asked how I was able to create the simple sorting feature found on the Vault page of my blog. Truthfully, it was done out of haste. Though I'll eventually run everything through a database and sort it that way, for now, I needed a quick and dirty way to do it with JavaScript. I'll show you what I did.

20 Minute Video Tutorial

Other Viewing Options

The Final jQuery

Updated a bit from the video.

var ulOptions = '';
var $links = $('#links');

$links.before(ulOptions)
  		   .children('li')
		   .addClass('all')
		   .filter('li:odd')
		   .addClass('odd');

$('#options li a').click(function() {
	var $this = $(this),
		type = $this.attr('class');

	$links.children('li')
		.removeClass('odd')
		.hide()
		.filter('.' + type)
		.show()
		.filter(':odd')
		.addClass('odd');
				
	return false;
});

Update: Sneaky Little Bug

"SFdude" found a bug where, if you click on the same item twice, the entire list will disappear! Luckily, I was able to determine the problem quickly. The issue was that after the first click, we applied a class of "selected" to the anchor tag. That is what was causing the hiccup. Because now - it had two classes that would not correspond to anything! The fix is to remove these two lines:

$('#options li a').removeClass('selected');
$this.addClass('selected');

Truthfully - they were unnecessary. We can just as easily use the a:focus selector in our stylesheet to accomplish this. :)

a:focus {
 font-weight: bold;
}

And that does it. I've updated the demo and the source code. Thanks to SFdude for finding that sneaky little bug.

So what are your thoughts? Disagree with this method? Is there a better way to do it - without a database? Let me know!

Thank you, Screencast.com!

Screencast.com
...for providing the hosting for these video tutorials.


Related Posts

Check out some more great tutorials and articles that you might like

Enjoy this Post?

Your vote will help us grow this site and provide even more awesomeness

Plus Members

Source Files, Bonus Tutorials and
More for $9 a month for all TUTS+
sites in one subscription.

Join Now

User Comments

( ADD YOURS )
  1. PG

    siempre September 24th

    Nice tuts. As always !

    ( Reply )
  2. PG

    lawrence77 September 24th

    in the overview u tell to the users that u renew ur site :P

    Gonna see the video, i hope as usual it rocks… :D

    Where is the download link for a offline viewers like me? :(

    ( Reply )
    1. PG

      Jeffrey Way September 24th

      Thanks for reminding me! Just added the download link underneath the video. :)

      ( Reply )
      1. PG

        lawrence77 September 24th

        you are always welcome JW!
        Thanks for the tut… :)

      2. PG

        C.44 September 24th

        Any chance these vids will be popping up on iTunes soon ? Still waiting for the code igniter vids aswell.

        Btw, this tut has convinced me to finally start learning jquery… about time lol.

  3. PG

    etrnly September 24th

    Nice job this is very useful!

    ( Reply )
  4. PG

    Mike Schneider September 24th

    I like the idea…I always assumed you would need access to a db to sort/filter. Really gets me thinking about what else I’m doing that could be done easier.

    ( Reply )
    1. PG

      Jeffrey Way September 24th

      Hey Mike. Usually – you will do it via an AJAX request to your database. But this is a quick – and static – alternative. :)

      ( Reply )
      1. PG

        Abhijit September 25th

        Yes, loading too many rows of data and hiding showing with js may be costly in terms of resources.

      2. PG

        Bretticus September 25th

        Seriously though, you are returning an extra 50 lines of short phrases at the most (if you return thousands of lines, you may be out of control.) We’re not talking major resources here (especially in the example: the demo and the actual implementation on Jeff’s site.)

      3. PG

        Bretticus September 25th

        Besides, I’d rather have that content on my page for the search engine to spider. ;)

  5. PG

    Barry September 24th

    Wow! Rehash much? You have another tutorial almost like this.

    http://net.tutsplus.com/tutorials/javascript-ajax/creating-a-filterable-portfolio-with-jquery/

    ( Reply )
  6. PG

    Javed Gardezi September 24th

    Thanks JW!!
    Keep going on :)

    ( Reply )
  7. PG

    Roland September 24th

    In TextMate, Ctrl-Shift-D is your friend (Duplicate line) I find it faster than copy/paste when mocking things up :)
    Another useful TextMate key is Ctrl-Shift-W to wrap something in a tag (it defualts to a paragraph… very useful to wrap things in a list item as well as anchor link because it does the both the opening and closing tags in the wrap :)

    I don’t know why you called #e5e5e5 a grayish blue… by my reckoning it is just 90% gray – whenever R = G = B it’s going to be white, a shade of gray, or black.

    ( Reply )
    1. PG

      Roland September 24th

      90% is also to subtle to show up on screencasts btw :/

      ( Reply )
    2. PG

      Jeffrey Way September 24th

      It looks a bit blue to me – but maybe I’m color blind. :) It’s just a hex value that was at the top of my head.

      ( Reply )
      1. PG

        Cameron Olivier October 5th

        Looks like you need to calibrate your screen ;) hehe by definition, it’ll be a flat gray :)

  8. PG

    SFdude September 24th

    Nice!

    But, if you
    1) load the Demo page
    2) click ALL
    3) click ALL again

    all entries disappear (ie: blank list with no entries),
    and there’s no way to make them ALL appear again
    by simple clicking ALL.

    Well, I believe ALL should show “All entries” when clicked, right?

    ( Reply )
    1. PG

      Jeffrey Way September 24th

      Oh no. :) Thanks for finding that. I’m pretty sure I know what the problem is. It’s because when it’s reclicked, the anchor tag now has two classes instead of. I’m fixing the code right now.

      ( Reply )
      1. PG

        Jeffrey Way September 24th

        Okay, fixed. Thanks! The demo/src/article have been updated. :)

  9. PG

    nanochrome September 24th

    Will the latest CI and this screencast be in iTunes soon?

    ( Reply )
  10. PG

    SFdude September 24th

    Thank you Jeffrey
    for that quick fix! (your post above).
    Works great now – easy, clear & simple to implement…

    SFdude

    ( Reply )
  11. PG

    Cracks September 24th

    Is there a method of doing this where it will (at least) degrade with some sort of grace ..?

    ( Reply )
    1. PG

      Jeffrey Way September 24th

      Just responded to you below.

      ( Reply )
  12. PG

    Michael Irwin September 24th

    Great tut! I have done something similar, and instead of putting the ul for buttons in a javascript variable, I had it just in the text, and had the CSS hide it. The jQuery would then show it. But, either way works.

    Thanks for the tut!

    ( Reply )
  13. PG

    Cracks September 24th

    nb: i know you’re method is “quick & dirty”, and isn’t supposed to be graceful. i’m just wondering if anyone knows of a more graceful method of achieving the same filter-type search..?

    ( Reply )
    1. PG

      Jeffrey Way September 24th

      @Cracks – What more are you looking for. This filtering isn’t something that can be done with just CSS. Without JavaScript disabled, it just turns into a normal list.

      What more are you expecting?

      ( Reply )
      1. PG

        Aqib Mushtaq September 25th

        “Without JavaScript disabled”… lol, you mean With Javascript Disabled.

  14. PG

    Ashit Vora September 24th

    Hi Jeff,
    I have been waiting for CI since long… :(

    ( Reply )
    1. PG

      Khalil September 25th

      Hi Jeff,
      Me too, Please come soon with the pagination tutorial into CI + jQuery.
      waiting….

      ( Reply )
  15. PG

    Mathew September 24th

    swapping show() for slideDown() and hide() for slideUp() makes the filtering process a little cooler, needs a little more work to make it perfect but you get the idea

    ( Reply )
  16. PG

    Deoxys September 25th

    Pretty easy, but ok.

    ( Reply )
  17. PG

    zaiful September 25th

    I don’t think Jeffrey you really think about the readers from poor internet speed regions. I am from Bangladesh and I know about 20-30 from my area who love nettuts and I guess a large number of people from my country regularly follow nettuts and other envato sites.

    We are not able to see these screencasts online with our speed, so normally we use to download them and see them later. Don’t know why these new screencasts from screencast.com are very hard to download, the download speed is too slow and in the end of download it normally shows size mismatch error and sometime timeout error.

    We people here browse internet with 20-30KB speed, previously we could download blip.tv’s flvs at a goot speed of 20KB+ but these screencast.com’s mp4s don’t cross 10-12KB and in the end they just reduce to 1-2KB and cause those errors.

    I guess you may have some advertise agreement thats why you are promoting screencast.com as I didn’t see any wrong with blip.tv, many with agree with it. They were just fine…

    Anyway, I hope you will provide an alternative source for those screencasts.You go with screencast, they are also fine. You just, please, download the mp4 and upload it to another host like rapidshare,megashare or any host of your own etc…Someone uploaded the CI Day-5 CRUD screencast to rapidshare and we could download it from there. We are really missing your great screencasts. I hope you will take some time to think about poor visitors like us and will let us to learn these useful things.

    ( Reply )
    1. PG

      Jeffrey Way September 25th

      A few of you mentioned issues with the download speed – which is confusing. But yes – I’ll also be uploading to Blip.tv as well – as an alternative for those with lower download speeds. :)

      ( Reply )
      1. PG

        zaiful September 25th

        Thanks a lot for your reply..I again tried to download this screencast few hours ago, was going outside so thought to keep my PC busy to download it. I thought it may work this time, who knows?!? (as I thought 9-10 times before for the last 2 CI screencasts). Came back home after 2 hours and that same old story :D Size mismatch error!! Anyway, hope you upload them to Blip.tv and we will get the chance to see them and learn from them. I am really missing them. Please do it man, will be really grateful :)

  18. PG

    Web 2.0 September 25th

    Great tip..

    ( Reply )
  19. PG

    jem September 25th

    Nice tip, I like using CSS classes for filtering like this.

    This might have just been beyond the scope of this tutorial, but it would probably be a better practice (especially if there’s the possibility of being lots of these elements) to cache some of the work thats being done so you’re not having to collect the same elements over and over again.

    ( Reply )
  20. PG

    Brett Jankord September 25th

    Nice, quick, and easy. I’ve been thinking about adding a filtering system to my portfolio when I add more projects. This will come in handy.

    ( Reply )
  21. PG

    Bretticus September 25th

    Another fine tutorial that shows how you can use jquery to provide interaction to your user while maintaining best search engine practices.

    Excellent! And Thanks again!

    ( Reply )
  22. PG

    Bretticus September 25th

    By the way…where do these people come from demanding the “next CI” tutorial that is being offered to them completely free? Is this an example of what has been coined the “me generation?” It’s a strange phenomenon to me I guess. That is, people believing they have the right to demand your time without any attachment nor compensation. :)

    ( Reply )
  23. PG

    Jeff Adams September 25th

    I like it’s simplicity – I mean if you just have lists that you want filterable then why pay for hosting for PHP support etc? Good tutorial as always.

    ( Reply )
  24. PG

    Aditu September 25th

    Maybe phpQuery tutorial next time?

    ( Reply )
  25. PG

    Timo Körber September 25th

    nice one… great inspiration…

    ( Reply )
  26. PG

    Quicken Websites September 26th

    I have seen a designers portfolio done in a similar way.

    ( Reply )
  27. PG

    almulaiki September 27th

    thanks Mr. Jeffery , what attract me to your screencasts is your genorisity when deliver your ideas, truthfully you are the best developer I have learned from.
    go on ….

    ( Reply )
  28. PG

    IgnacioRV September 27th

    Thanks Jeffrey, I’ve learned a lot of jQuery with this :)

    ( Reply )
  29. PG

    Neil September 28th

    Great tute. Glad to see the return of the iTunes feed too. Hopefully some of the other screencasts will be published there too as I’m missing CI from Scratch Day 5 and 6. Easier to watch the iTunes video and test in the browser at the same time.

    ( Reply )
  30. PG

    orves September 30th

    Hi Jef, once again a great tut!
    I wish to use this in my custom made CMS and therefore I have a question;

    Is it possible to filter through a multi level UL-LI structure like so

    [code]

    How to do something great with PHP and HTML

    JS
    HTML
    PHP

    Users of my CMS get the possibility to manage a multi-language website where every page relates to a curtain language which I then would use in the LI class.

    Your script works fine on a one level structure and I would like to know how I and others can implement this in a multi level structure.

    I hope you, or an other reader, can find the time to answer my question.

    ( Reply )
    1. PG

      orves September 30th

      My code srewed up so here it is again:

      How to do something great with PHP and HTML

      JS
      HTML
      PHP

      ( Reply )
  31. PG

    Quicken Websites October 1st

    Great tutorial! thanks! Very useful!

    ( Reply )
  32. PG

    Yves October 17th

    Great Tutorial!

    I have one question:

    Everything works properly. However, I have a list that contains more than one list and a couple of div and when I click to filter, it adds me “style =” display: none “to all child elements … how can I fix this?

    thank you very much

    ( Reply )
  1. Arrow
    Gravatar

    Your Name
    October 17th