Elvis
Elvis

Reputation: 39

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.

Upvotes: 3

Views: 76

Answers (2)

nisar
nisar

Reputation: 1065

make a function which had similar functionality, then pass a parameter as a class or id

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

});

Upvotes: 2

Marvin Medeiros
Marvin Medeiros

Reputation: 252

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'));
});

Upvotes: 4

Related Questions