1

Here's my current if/else statement:

var current_class = $(this).closest("article").attr("class")

if (current_class == 'opened')
{
  $(this).closest("article").removeClass('opened');
  $(this).closest("article").addClass('closed');
}
else
{
  $(this).closest("article").removeClass('closed');
  $(this).closest("article").addClass('opened');
}

Is there a shorter way to write all of that? Just seems...overweight. :)

4 Answers 4

6

Use

.toggleClass()

Here is an example http://api.jquery.com/toggleClass/

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

1 Comment

It seems that .toggleClass() works with two classes. i.e. .toggleClass('opened closed'). Example: jsfiddle.net/xaHTn/4
2

IMO this is the cleanest and still clearest solution:

var current_class = $(this).closest("article");
if (current_class.hasClass('opened'))
{
  current_class.removeClass('opened').addClass('closed');
}
else
{
  current_class.removeClass('closed').addClass('opened');
}

3 Comments

the cleanest would be to use only 1 class (open by default?) then only have the class close. Then use toggle like cps7 suggested.
hasClass() is an important change. Just doing a string comparison of the class attribute will break if the element has other classes added.
I would assign a local variable for $(this).closest("article") to avoid doing the DOM lookup twice. That's not a style thing though, it's a speed thing.
0

maybe something like:

var current = $(this).closest('article'); // no need to run the selector over and over
var current_class = current.attr('class');
current.removeClass('opened closed').addClass(current_class=='opened'?'closed':'opened');

Comments

0
$(this).closest("article").toggleClass('opened').toggleClass('closed');

1 Comment

You can get a state problem if the item somehow contains both opened and closed.

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.