Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set JQuery .show / .hide without repeating Div selectors

I want to pass this function a True or a False and have the elements listed show (true) or hide (false) on this input.

I am currently using this function...

        function SetElementVisibility(visible) {
        if (visible) {
            $("#Div1").show("slow");
            $("#Div2").show("slow");
            $("#Div3").show("slow");
        }
        else {
            $("#Div1").hide("slow");
            $("#Div2").hide("slow");
            $("#Div3").hide("slow");
        }
    }

But i would prefer to not repeat myself by naming the Div's for each outcome.

How can i refactor this into a more DRY (Don't Repeat Yourself) example?

Thanks, Kohan

like image 573
4imble Avatar asked Nov 29 '22 18:11

4imble


1 Answers

Use square-bracket notation to pick a method name depending on the visible variable:

$('#Div1, #Div2, #Div3')[visible? 'show' : 'hide']('slow');
like image 75
bobince Avatar answered Dec 05 '22 05:12

bobince