I have a web page that contains a set of elements that are marked with metadata using HTML5’s “data-” tag. Each element represents a specific course or program at a school. Here’s an example of what the set of elements can look like:
<div class="courseBox" data-type="course" data-location="campus">info about this particular course</div>
<div class="courseBox" data-type="program" data-location="campus">info about this particular course</div>
<div class="courseBox" data-type="course" data-location="distance">info about this particular course</div>
<div class="courseBox" data-type="program" data-location="distance">info about this particular course</div>
As you can see each element is either a course (short single course) or a program (a full education that spans over several years). Furthermore, each element is eithar campus (on campus) or distance (distance learning).
In the interface for this page the user has four buttons that can either be on/true or off/false. The four buttons are:
Course | Program | Campus | Distance
When the page loads all four buttons are on/true since the page displays all courses and programs, both on campus and distance learning.
When the user clicks one of the buttons, I want to use jQuery to hide all the elements that no longer match the criteria; in other words: a filter.
At first this seemed like an easy task. Just write something along the lines of:
$("#courseButton").toggle(function(){
$("courseBox[data-type='course']").hide();
},
function(){
$("courseBox[data-type='course']").show();
});
This works fine as long as the two different ways of categorizing the elements don’t collide. But consider this case:
-
The user first clicks the “Course”
button, which hides all the courses
(marked “courses”). -
Then clicks the “Distance” button
which hides all elements marked
“distance”. -
The user then clicks the “Course”
button again, which will show all
element marked with “courses” including
those that are marked “distance”,
despite the fact that they are
supposed to be hidden.
My question now is: how do I create a filter function using jQuery that will function properly eventhough there are two different (intersecting) ways of categorizing the elements?
Thanks in advance!
/Thomas Kahn
Actually, your situation is a bit trickier. You have two groups, type and location. You need the intersection of type and location.
This means selecting all of the items of the selected type(s) and then filtering out all of the ones that are not of selected distance(s) or vice versa.
Here is an example:
http://jsfiddle.net/jtbowden/qjpctye4/
I actually start with all items, remove any that are of a type that is not selected, and then only show those which are of a distance selected.