1

I'm looking for some newbie Javascript help.

I've got a series of simple functions which add and remove some slider content using JQuery, following a click from a callout. How can this be rewritten to work with any category ('cat1' etc) content?

$('.cat1_link').click(function(event) {
    $('.category_slides li').fadeOut();
    $('.cat1').fadeIn();
    $('article.listitem').removeClass('current');
    $('article.listitem.cat1').addClass('current');
});
$('.cat2_link').click(function(event) {
    $('.category_slides li').fadeOut();
    $('.cat2').fadeIn();
    $('article.listitem').removeClass('current');
    $('article.listitem.cat2').addClass('current');
});
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Reg T
  • 55
  • 6
  • Very likely that this can be refactored. Can you edit the question and add the relevant `HTML` please? The structure of your page will help in choosing generic selectors that will work for all of the categories, possibly avoiding using string concatenation in the selectors. – andyb Apr 30 '13 at 09:42

2 Answers2

4

Change your HTML to:

<a class="cat_link" data-category="cat1" ...>

Then you can write the jQuery as:

$('cat_link').click(function(event) {
    var cat_class = $(this).data('category');
    $('.category_slides li').fadeOut();
    $('.'+cat_class).fadeIn();
    $('article.listitem').removeClass('current');
    $('article.listitem.'+cat_class).addClass('current');
});
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Thanks all - I followed Barmar's example and got this working perfectly across the site. – Reg T May 05 '13 at 18:26
2

Extract the "stuff" that varies and create a generic function for the "stuff" that stays the same. A first stab would be something like

$.each(['cat1', 'cat2'], function (i, e) {

    $('.' + e + '_link').click(function(event) {
        $('.category_slides li').fadeOut();
        $('.' + e).fadeIn();
        $('article.listitem').removeClass('current');
        $('article.listitem.' + e).addClass('current');
    });

});

There could be more succinct ways to do this, depending on what your markup looks like (and whether you have any control to change it).

Russ Cam
  • 124,184
  • 33
  • 204
  • 266