I’ve got some code on my site that displays a list of articles on a blog as follows (there will be multiple objects with the same category):
<ul class="article category1">
<li> etc
<li>
</ul>
<ul class="article category2">
<li> etc
<li>
</ul>
<ul class="article category3">
<li> etc
<li>
</ul>
I’ve got some jQuery code that filters the list so you only get one category displayed as follows:
$("#showall").click(function() {
$("ul.article").show('fast');
});
$("#showcategory1").click(function() {
$("ul.article.category1").show('fast');
$("ul.article").not("ul.category1").hide('fast');
});
When you click on the relevant link, i.e.
<a id="showall">All</a>
<a id="category1">Category 1</a>
Currently I’ve got about 9 categories to deal with and so 10 snippets of jQuery which seems horribly inefficient (it is horribly inefficient). I have no idea how to generalise the code so that it takes in the ID (or perhaps the class) of the anchor and then applies it to the relevant lists. Any help please?
Thanks!
You can commonalize the code by working from a list of categories:
This doesn’t change the runtime behavior, just reduces the amount of code needed to create the functions in the first place. The key idea here is that the jQuery selectors don’t have to be literal strings, they can be constructed from literals and variables.