4
\$\begingroup\$

I am pretty new to Javascript and trying to make a really simple tabs element which is just hiding and showing sections depending on which button is clicked. I know that this is a terrible way of writing this, as there is so much repetition, how do I make this code cleaner? (It has to be either Vanilla JS or JQuery as it's for a WordPress site).

const tab1 = $('.tab-1');
const tab2 = $('.tab-2');
const tab3 = $('.tab-3');
const tab4 = $('.tab-4');

$('.button-1').click(function() {
    tab1.addClass('active');
    tab2.removeClass('active');
    tab3.removeClass('active');
    tab4.removeClass('active');

    tab1.fadeIn();
    tab2.hide();
    tab3.hide();
    tab4.hide();
});

$('.button-2').click(function() {
    tab1.removeClass('active');
    tab2.addClass('active');
    tab3.removeClass('active');
    tab4.removeClass('active');

    tab1.hide();
    tab2.fadeIn();
    tab3.hide();
    tab4.hide();
});

$('.button-3').click(function() {
    tab1.removeClass('active');
    tab2.removeClass('active');
    tab3.fadeIn('active');
    tab4.removeClass('active');

    tab1.hide();
    tab2.hide();
    tab3.fadeIn();
    tab4.hide();
});

$('.button-4').click(function() {
    tab1.removeClass('active');
    tab2.removeClass('active');
    tab3.removeClass('active');
    tab4.addClass('active');

    tab1.hide();
    tab2.hide();
    tab3.hide();
    tab4.fadeIn();
});
\$\endgroup\$

1 Answer 1

4
\$\begingroup\$

Short review to make this more DRY

  • Review the documentation on https://api.jquery.com/toggle/, this often helps with code like this

  • Know that you can select multiple id's by separting selectors with a comma in jQuery

  • You can chain jQuery commands, which can lead to either more or less readable code, it's an art. In this code, I feel there is not enough chaining Knowing this, you can rewrite to something like this;

    const tab1 = $('.tab-1');
    const tab2 = $('.tab-2');
    const tab3 = $('.tab-3');
    const tab4 = $('.tab-4');
    const allTabs = $('.tab-1,.tab-2,.tab-3,.tab-4');
    
    $('.button-1').click(function() {
        allTabs.removeClass('active').hide();
        tab1.addClass('active').fadeIn();
    });
    
    $('.button-2').click(function() {
        allTabs.removeClass('active').hide();
        tab2.addClass('active').fadeIn();
    });
    
    $('.button-3').click(function() {
      allTabs.removeClass('active').hide();
      tab3.addClass('active').fadeIn();
    });
    
    $('.button-4').click(function() {
      allTabs.removeClass('active').hide();
      tab4.addClass('active').fadeIn();
    });
    
\$\endgroup\$

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.