0

I have this code:

$("#Editing").click(function(){
  if ($(this).attr("class","OptionsOpt-On")) 
    {$(this).attr("class","OptionsOpt-Off"); Edit = false;}

  else if ($(this).attr("class","OptionsOpt-Off")) 
    {$(this).attr("class","OptionsOpt-On"); Edit = true;}
});

I have searched and haven't been able to find a similar answer because all the ones that I found had problems with the code that I have identified to not be in my code. I don't know why the "else if" doesn't work, but if I change it to an if, it works just fine...

2 Answers 2

4

attr with 2 arguments = setter = returns a jQuery object which is always a truthy value.

You should use it as a getter and do comparison:

if ( $(this).attr("class") === 'OptionsOpt-On' ) {
//...

Though .hasClass() may be more appropriate in this case:

if ( $(this).hasClass('OptionsOpt-On') ) {
    //...
} else {
    //...
}

As your element can't have both classes at the same time, you don't need a second if in the else.


Also assuming the element starts with one of the classes you can use .toggleClass() to toggle both classes without needing a conditional statement:

$("#Editing").click(function(){
    $(this).toggleClass('OptionsOpt-On OptionsOpt-Off');
    Edit = $(this).hasClass('OptionsOpt-On');
});

Fiddle

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

2 Comments

The OP should also note that the target element has to has at least either class assigned to it before the .click() event, or else the if-else will not work because neither conditions are satisfied.
@Terry Yes, nicely noted. =]
1

Maybe you are trying to do this:

if ($(this).attr("class")=="OptionsOpt-On")

The .attr function when used with two arguments works as a setter, while as a getter with just one argument.

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.