0

I ran across an interesting problem today (Firefox 44). I have a conditional statement that is evaluating the else if statement after evaluating a 'true' if statement. Take an example:

The initial state of .dataRow is collapsed. When a dataRow is clicked the first condition is found to be true and the class is changed to expanded. Next the else if statement is evaluated and the class is changed back to collapsed because it changed to expanded in the previous condition! Why in the world would the else if statement be evaluated after the first condition is found true?

    $("div").on("click", "div.dataRow", function(){
    if ($(this).hasClass("collapsed"))
    {
        $(this).removeClass("collapsed").addClass("expanded");
    }
    else if($(this).hasClass("expanded"))
    {
        $(this).removeClass("expanded").addClass("collapsed");   
    }
    });

I had to put return statements in the conditions to get the function to work properly.

    $("div").on("click", "div.dataRow", function(){
    if ($(this).hasClass("collapsed"))
    {
        $(this).removeClass("collapsed").addClass("expanded");
                return false;
    }
    else if($(this).hasClass("expanded"))
    {
        $(this).removeClass("expanded").addClass("collapsed");   
                return false;
    }
    });

EDIT

Here is a simplified reproduction of the problem jsFiddle

7
  • That might be because of event propagation, cannot comment anything without seeing your html Commented Mar 5, 2016 at 14:57
  • No else part is evaluated if the if statement evaluated to true. Create a MCVE if you think otherwise. Commented Mar 5, 2016 at 14:59
  • Maybe you bind event twice and you have html like <div><div><div class="dataRow"></div></div></div> Commented Mar 5, 2016 at 15:00
  • Can you create a fiddle? Commented Mar 5, 2016 at 15:01
  • @jcubic I think you may be correct. The <div> in question is nested inside another <div>. I am a little confused that I would see this behavior when using firebug and setting breakpoints. I will try to reproduce with fiddle. Commented Mar 5, 2016 at 15:03

1 Answer 1

1

I am not into removeClass and addClass of jQuery right now. But each "else if" block condition is evaluated. As you add the class in the first block, the second condition is always true after that.

If you have only two conditions, I would advise you to only use "else". That would protect the second block from being executed, if the first was executed.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.