Client side filtering data with jQuery
In this tutorial we are going to make a really easy to build filtering system with jQuery. There will be no AJAX or PHP, just HTML and jQuery.
The first demo is styled version of this tutorial, and the second demo is non styled version.
How does it look?
Yes, that’s it. No CSS in the tutorial, but the source code and the demo include a styled version. You can see the demo here
That’s the styled version. You can see the demo here
How will it work?
The filter links will have an ID that matches a certain category, and the list items that hold our content will have CLASSES that match one or more category. So when a filter link is clicked jQuery will get the ID of it which is a certain category and will hide all list items that don’t have that category in their classes.
<!-- the filters div -->
<div id='filters'><a href='#'>All</a> <a href='#' id='bestof'>Best Of</a> <a href='#' id='jquery'>jQuery</a> <a href='#' id='php'>PHP</a> <a href='' id='html'>HTML</a> <a href='#' id='css'>CSS</a></div>
<!-- the content div -->
<!-- the unordered list where we store the content in list items -->
<li class='bestof'>Best of September- 10 web development articles and tutorials</li>
<li class='jquery php'>14 jQuery and non-jQuery Rich Text Editors</li>
<li class='php'>How to know where your visitors are coming from</li>
<li class='php'>How speed improving using single quotes instead of double quotes really is</li>
<li class='jquery html'>Automatic input field focus on page load</li>
<li class='jquery php'>Checking username availability with ajax using jQuery</li>
<li class='jquery css html'>Hover effect with jQuery and CSS</li>
<li class='jquery css html'>Zebra stripes with jQuery and CSS</li>
<li class='jquery html'>Maxlength for textarea using jQuery</li>
//when a link in the filters div is clicked...
//prevent the default behaviour of the link
//get the id of the clicked link(which is equal to classes of our content
var filter = $(this).attr('id');
//show all the list items(this is needed to get the hidden ones shown)
$('#content ul li').show();
/*using the :not attribute and the filter class in it we are selecting
only the list items that don't have that class and hide them '*/
$('#content ul li:not(.' + filter + ')').hide();
That’s it. And this is the easiest way to filter data like this, as far as i know, if you know about an easier way i will be thrilled to hear about it
If you want you can subscribe to TutsValley RSS Feed or follow us on Twitter to be informed when a new tutorial comes out. Thank you.
- Cool navigation menu made with JQuery
- Checking username availability with ajax using jQuery
- Making an infinite JQuery carousel
- Making A Cool Thumbnail Effect With Zoom And Sliding Captions
- Making a Cool Spotlight Effect with jQuery
Did you absolutely LOVE this article... share it!