I want to learn best practices with jQuery and how to avoid code reptition and use elegant code.
I’ve written:
<script type="text/javascript">
// Change the category name with the filter
$(function() {
// Featured
$('.featured').click(function() {
$('.categoryTitle h1').hide().html('Featured').fadeIn('slow');
});
// Web
$('.web').click(function() {
$('.categoryTitle h1').hide().html('Web').fadeIn('slow');
});
// Brand
$('.brand').click(function() {
$('.categoryTitle h1').hide().html('Brand').fadeIn('slow');
});
// Print
$('.print').click(function() {
$('.categoryTitle h1').hide().html('Print').fadeIn('slow');
});
// All
$('.all').click(function() {
$('.categoryTitle h1').hide().html('All').fadeIn('slow');
});
});
</script>
HTML
<ul id="filters">
<li><a class="featured" href="#" data-filter=".feature-this">Featured</a></li>
<li><a class="web" href="#" data-filter=".category-web">Web</a></li>
<li><a class="brand" href="#" data-filter=".category-brand">Brand</a></li>
<li><a class="print" href="#" data-filter=".category-print">Print</a></li>
<li><a class="all" href="#" data-filter="*">Show All</a></li>
</ul>
<div class="categoryTitle"> <h1>Featured</h1> </div>
Is this as elegant as it can be, or am I missing how to stop diving into the DOM as much?
Note I am using Isotope, a jQuery plugin.
Edit None of the answers are currently changing categoryTitle, but I did ommit that it has a default value of Featured.
try this demo