Elvis Elvis - 7 months ago 23
Javascript Question

How to optimize this javascript duplicates

I wrote this code, but since I'm just starting to learn JS, can't figure out the best way to optimize this code. So made a duplicates for every if statement.

$(function() {
var lang = $(".lang input[type='checkbox']");
var gender = $(".gender input[type='checkbox']");
if(lang.length == lang.filter(":checked").length){
$('.lang').hide();
$('.lang-all').click(function(){
$('.lang-all').hide();
$('.lang').slideToggle(200);
});
} else {
$('.lang').show();
$('.lang-all').hide();
}

if(gender.length == gender.filter(":checked").length){
$('.gender').hide();
$('.gender-all').click(function(){
$('.gender-all').hide();
$('.gender').slideToggle(200);
});
} else {
$('.gender').show();
$('.gender-all').hide();
}
});


So this is my code, as you can see on line 15 if(gender... I have a duplicate of previous code, just changed variable from "lang" to "gender". Since I have more that two variables, I don't want to make duplicate of code for every each of them, so I hope there is a solution to optimize it.

Answer

You can write a function to let your code more abstract, see:

function isChecked(obj, jq1, jq2){
    if(obj.length == obj.filter(":checked").length){
        jq1.hide();
        jq2.click(function(){
            jq2.hide();
            jq1.slideToggle(200);
        });
    } else {
        jq1.show();
        jq2.hide();
    }
}

//Your jQuery code, more abstract
$(function() {
    var lang = $(".lang input[type='checkbox']");
    var gender = $(".gender input[type='checkbox']");

    isChecked(lang, $('.lang'), $('.lang-all'));
    isChecked(gender, $('.gender'), $('.gender-all'));
});
Comments