In jQuery 1.7+, you should use on. The below examples binds the event to the .filter_categories
element, working like a delegate event.
A delegated-events approach attaches an event handler to only one element, the .filter_categories
, and the event only needs to bubble up one level (from the clicked li
to .filter_categories
).
Method 1
Assuming there is a sequential naming convention that you can use such as in your question:
$(".filter_categories").on("click", "li", function() {
var articleClass = ".category-cat-" + ($(this).index() + 1);
$(articleClass).fadeOut();
});
Demo: http://jsfiddle.net/hadynz/yxjNb/1/
Method 2
Assuming that your different article names and corresponing articles will not have any particular pattern, you can use the following:
<ul class="filter_categories">
<li><a href="#" data-article="science">Cat 1</a></li>
<li><a href="#" data-article="geography">Cat 2</a></li>
<li><a href="#" data-article="math">Cat 3</a></li>
<li><a href="#" data-article="history">Cat 4</a></li>
</ul>
<article class="science">
Science Article
</article>
...
$(".filter_categories").on("click", "li a", function() {
$("." + $(this).data('article')).fadeOut();
});
Demo: http://jsfiddle.net/hadynz/yxjNb/2/