1
\$\begingroup\$

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") && !(clicked == "Text2") && !(clicked == "Text3") ) 
        {
            $("#Text1, #Text2, #Text3").css("opacity", "1");  // return to default state
        }   

 };
\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$
  • \$\begingroup\$ Thanks mega, couple issues: using $(this) doesn't work for me, but replace it with $("#" + clicked) will. Also, the opacity does not automatically restore itself, I still need to explicitly call another function to get the opacity to return. \$\endgroup\$ – DeBraid Jan 20 '14 at 21:35
  • \$\begingroup\$ I'd be interested in seeing an example where $(this) doesn't wrap the same element as $("#" + this.id). Do you have multiple elements with the same id on your page (quite a poor practice)? If you'd set up a jsfiddle or jsbin I'd play around with the code some more \$\endgroup\$ – megawac Jan 21 '14 at 0:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.