Tom Millard
Tom Millard

Reputation: 533

jQuery toggleClass with conditional

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.

Upvotes: 2

Views: 1431

Answers (2)

Richard Neil Ilagan
Richard Neil Ilagan

Reputation: 14747

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.

Upvotes: 0

Mukesh Soni
Mukesh Soni

Reputation: 6668

$('#myDiv.hidden').toggleClass('shown hidden');

Upvotes: 14

Related Questions