ewill ewill - 5 months ago 10
Javascript Question

Having trouble applying D.R.Y. to my jQuery

I need help simplifying my code. I'm trying to apply the D.R.Y. principle as best as I can and I'm having trouble. Any help would be greatly appreciated.

$('document').ready(function(){
'use strict';

var body = $('body');

body.find('#button1').click(function(){
body.find('#item1').add('#item2').fadeOut();
body.find('#item3').fadeIn();
body.find('#button1').removeClass('btn-info').addClass('btn-default');
body.find('#button2').removeClass('btn-default').addClass('btn-info');
});

body.find('#button2').click(function(){
body.find('#item3').fadeOut();
body.find('#item1').add('#item2').fadeIn();
body.find('#button2').removeClass('btn-info').addClass('btn-default');
body.find('#button1').removeClass('btn-default').addClass('btn-info');
});
});


Thank you in advance!

pol pol
Answer

In addition to using just $ for accessing elements that are unique, you might also like this as an improvement for reuse and readability,

function makeInfo(id) {
  $(id).removeClass('btn-default').addClass('btn-info');
}
function makeDefault(id) {
  $(id).removeClass('btn-info').addClass('btn-default');
}

$('document').ready(function(){
    'use strict';

    $('#button1').click(function(){
         $('#item1').add('#item2').fadeOut();
         $('#item3').fadeIn();
         makeInfo('#button2');
         makeDefault(this);             
    });

    $('#button2').click(function(){
        $('#item3').fadeOut();
        $('#item1').add('#item2').fadeIn();
        makeInfo('#button1');
        makeDefault(this);             
    });
});
Comments