SMacFadyen
SMacFadyen

Reputation: 3165

Can I improve this jQuery code repetition?

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

Answers (5)

GajendraSinghParihar
GajendraSinghParihar

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

coolguy
coolguy

Reputation: 7954

$(document).ready(function(){
   $('ul#filters li a').click(function(){
           $('.categoryTitle h1').hide().html($(this).text()).fadeIn('slow')

   });
});

Upvotes: 0

insertusernamehere
insertusernamehere

Reputation: 23580

It's as simple as this:

  $('#filters a').click(function() {
        $('.categoryTitle h1').hide().html($(this).text()).fadeIn('slow');
  });

Upvotes: 0

chrisfrancis27
chrisfrancis27

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

svennergr
svennergr

Reputation: 810

function change(id){
$('.categoryTitle h1').hide().html(id).fadeIn('slow');
}

Upvotes: 1

Related Questions