Looking to create Javascript that acts like a filter on a list of divs. For instance, here's the intended markup...
<a href="#" onclick="">Filter Item 1</a>
<a href="#" onclick="">Filter Item 2</a>
<a href="#" onclick="">Filter Item 3</a>
<a href="#" onclick="">Filter Item 4</a>
<a href="#" onclick="">Filter Item 5</a>
<div class="1">Item 1</div>
<div class="1">Item 1</div>
<div class="2">Item 2</div>
<div class="3">Item 3</div>
<div class="1">Item 1</div>
<div class="4">Item 4</div>
<div class="4">Item 4</div>
<div class="1">Item 1</div>
<div class="5">Item 5</div>
I want to be able to click on the link for Item 1, and show only Item 1 divs and hide all other divs, click the link of Item 2, and show only Item 2 divs and hide all other divs and so on. I've seen several similar scripts but nothing that seemingly turns divs matching the class on/off in this manner.
Very simple solution:
This, ofcourse, will hide all the other div's on page, so you should give the all some other class or put inside another div. Then the code could be:
You can use jQuery's toggle. below is simple example:
Give them all another class (for example
item
) and then make the click hide allitem
and show all of the selected value.This can be done easily in Jquery, following should work for you, but you have to modify your html as following
and javascript as follows
Set an ID for each link, then assign an onclick event. There you can filter out divs using the clicked link ID.
Something like this (http://jsfiddle.net/pJRek/1/)
Markup:
And script:
If you setup your HTML as:
Then your jQuery code can be as simple as:
Of course, you will want to add a visual indication that a filter is toggled on and off. You may not want to associate the items with each link through id/classes, but instead use jQuery's data storage, depending on your needs.
A working example, tested in firefox, here: http://jsfiddle.net/mwolfetech/GetRV/
Edit: This solution is similar to Anto Binish Kaspar's, mainly differing only in how the html is modified. I think that the divs given are likely to be a good structure for your document anyway, and eliminates the need for extra classes for control. This is always a design decision--balancing div (for structural division) vs class (for, categories). Additionally, theres no need to extract the id from the event object as jQuery provides the
this
reference.