HowTo: filtering elements using classes
Posted by Sandro Paganotti in
Ruby on Rails -
comments are closed
Today class attributes are mostly used for styling pourposes but with the Prototype.js library and a little effort we can create a real working client-side filter. Consider the next code snippet:
<div id="item1" class="element red big heavy">Element 1</div>
<div id="item2" class="element yellow small heavy">Element 2</div>
<div id="item3" class="element red small light">Element 3</div>
<div id="item4" class="element yellow big light">Element 4</div>
and this simple CSS:
div.element_selected{
background: #666666;
}
Now consider an input type select like this:
<select id="filter_select" name="filter_select" onchange="emphatize_select('filter_select')">
<option value="red">red elements</option>
<option value="yellow">yellow elements</option>
<option value="big">big elements</option>
<option value="small">small elements</option>
<option value="heavy">heavy elements</option>
<option value="light">light elements</option>
</select>
Ok, everything is ready for the trick, with a few lines of javascript in a function called emphatize_select the job will be accomplished:
function emphatize_select(select_id){
select_element = document.getElementById(select_id)
class_name = select_element.options[select_element.selectedIndex].value
todelete = document.getElementsByClassName("element");
items = document.getElementsByClassName(class_name);
for(x=0;x<todelete.length;x++){
Element.removeClassName(todelete[x],"element_selected")
}
for(x=0;x<items.length;x++){
Element.addClassName(items[x],"element_selected")
}
}
It’s done :) obviously you can change the effect of the selected items or, with a very few changes, hide the items that doesn’t have the choosen class.
See you. Sandro.

