Toggle classes with Prototype and CSS
Using Prototype to toggle more than one div
The other day I needed to write a function that will hide and show summery content on a button click. Think of a blog where on a page you have like 5 blog entries with titles and excerpts. Imagine that you wanted to have a button for your users that will hide all the excerpts and only show blog entry titles on the page. You click the button once and the excerpts disappear, you click on it again and they reappear. These excerpts are in their own divs styled via a common css class called “excerpt”. If it was one element that you need to toggle, you can grab the id via getElementbyId or prototype $(’id’) function and toggle the damn thing via prototype toggle function.
But, there are many excerpts on the page, all in their own divs referenced via a class, so that method will not work. Initially, I thought about how to pull all these classes and still use the prototype toggle function, looking for something like getElementbyClass or getElementsbyClass. After some thought, however, I realized that there is a better way of solving this problem. There are functions for getElementsbyClass and I think prototype even has something like that build in (i’m still new to prototype) but I realized that there is just a better way to think about this problem. Since all my content is enclosed inside a div with id “content” I could just make on JavaScript call and use CSS to hide all elements with a class of “excerpt.”
To clarify, normally the class “excerpt” is set to display:block in CSS, but I add one more definition referenced via another class that I will call via JS:
.excerpt{display:block;}
.hideSummeries .excerpt{display:none;}
Now, the button just calls the prototype toggleClassName function:
$('content').toggleClassName('hideSummeries');
which goes to the DOM and attaches a class to the div with id “content” called “hideSummeries” and the CSS now tells all divs with class name excerpt to hide. Simple and nice, anyone needs to see this in action?
Popularity: 3%
If you enjoyed this post, please consider to leave a comment.












Comments
No comments yet.
Leave a comment