2

Does anyone know how to write the following in a neater, one line format? I'm sure it's possible but can't get very far with it.

if($('#myDiv').hasClass('hidden')){
   $('#myDiv').toggleClass('shown hidden');
}

Basically to only perform a toggle in one direction.

Many thanks,

Tom.

2
  • you want this in one line/.... it means Commented Jun 15, 2012 at 11:43
  • var result = $("#myDiv").hasClass("hidden") ? $('#myDiv').toggleClass('shown hidden') : false Commented Jun 15, 2012 at 11:45

2 Answers 2

14
$('#myDiv.hidden').toggleClass('shown hidden');
Sign up to request clarification or add additional context in comments.

3 Comments

@FelixKling: The selector guarantees that hidden is set, I think.
My apologies... (deleted my comment).
I knew it was going to be something stupidly simple. Thanks so much for the help everyone.
0

Maybe you can just call $('#myDiv').removeClass('hidden').addClass('shown') (and the corresponding inverse). It'll remove .hidden if it's there, and add .shown if it doesn't have it yet.

2 Comments

I take it that the idea is that the two classes shouldn't be assigned at the same time, and no other logic is dependent on the conditional. If the OP wants it in one line, it's a valid assumption. Don't know why, but hey.
.toggle is much simpler

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.