Changing html element with click event: how to restore default state of element using jQuery if/else statement I have a click event that calls a function (below, txtResize) which makes some CSS changes to html text. (Acts on Text of 3 unique elements).

Q: What is the best way to refactor this code to limit excessive if/else usage, AND restore the original state of ALL text elements once the user clicks away from this section?

Here is the partially working, ugly function:   

 function txtResize() {

        var clicked = this.id;

        if (clicked == "Text1")
        {
            $("#" + clicked).css("opacity", "1");
            $("#Text2, #Text3").css("opacity", "0.2");
        }
        else if (clicked == "Text2") 
        {
            $("#" + clicked).css("opacity", "1");
            $("#Text1, #Text3").css("opacity", "0.2");
        }
        else if (clicked == "Text3")
        {
            $("#" + clicked).css("opacity", "1");
            $("#Text1, #Text2").css("opacity", "0.2");
        }
         // code above is ok, below does not work

        else if ( !(clicked == "Text1") &amp;&amp; !(clicked == "Text2") &amp;&amp; !(clicked == "Text3") ) 
        {
            $("#Text1, #Text2, #Text3").css("opacity", "1");  // return to default state
        }   

 };
This is actually a pretty classic problem and I've addressed it in my code on numerous occasions. One of the simplest ways to do what you're doing is to just reset the state for all the elements and then correct it.

function txtResize() {
    var clicked = this.id;

    if ( clicked === "Text1" || clicked === "Text2" || clicked === "Text3" ) { //one of our text's were clicked
        $("#Text1, #Text2, #Text3").css("opacity", "0.2"); //reset them all to .2 opacity
        $(this).css("opacity", "1");//set this elements opacity to full
    } else { //its clearly not Text1/2/3
        $("#Text1, #Text2, #Text3").css("opacity", "1");  // return to default state
    }
 };


One nit-picky point is that we tend to prefer lower case in attributes for html. I would recommend text1, text2... or even better would be to give an id that better described what the element is on the page.