Reputation: 3165
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.
Upvotes: 1
Views: 182
Reputation: 9131
try this demo
<script type="text/javascript">
$(function() {
$('#filters').on('click', 'a', function() {
$(".categoryTitle").find("h1").hide().html($(this).text()).fadeIn('slow');
});
});
</script>
Upvotes: 1
Reputation: 7954
$(document).ready(function(){
$('ul#filters li a').click(function(){
$('.categoryTitle h1').hide().html($(this).text()).fadeIn('slow')
});
});
Upvotes: 0
Reputation: 23580
It's as simple as this:
$('#filters a').click(function() {
$('.categoryTitle h1').hide().html($(this).text()).fadeIn('slow');
});
Upvotes: 0
Reputation: 4536
This should do it:
<script type="text/javascript">
$(function() {
$('#filters').on('click', 'a', function() {
$('.categoryTitle h1').hide().html($(this).text()).fadeIn('slow');
});
});
</script>
Upvotes: 6
Reputation: 810
function change(id){
$('.categoryTitle h1').hide().html(id).fadeIn('slow');
}
Upvotes: 1