If I have class .A and class .B and want to switch in between on button click, what's a nice solution for that in jQuery? I still don't understand how toggleClass()
works.
Is there an inline solution to put it in onclick=""
event?
If I have class .A and class .B and want to switch in between on button click, what's a nice solution for that in jQuery? I still don't understand how toggleClass()
works.
Is there an inline solution to put it in onclick=""
event?
If your element exposes class
A
from the start, you can write:This will remove class
A
and add classB
. If you do that again, it will remove classB
and reinstate classA
.If you want to match the elements that expose either class, you can use a multiple class selector and write:
The easiest solution is to
toggleClass()
both classes individually.Let's say you have an icon:
To toggle between
fa-angle-down
andfa-angle-up
do the following:Since we had
fa-angle-down
at the beginning withoutfa-angle-up
each time you toggle both, one leaves for the other to appear.Here is a simplified version: (albeit not elegant, but easy-to-follow)
Alternatively, a similar solution:
Your
onClick
request:Try it: https://jsfiddle.net/v15q6b5y/
Just the JS à la jQuery:
I've made a jQuery plugin for working DRY:
You can just try it here, copy and run this in the console and then try:
Here's another 'non-conventional' way.
An example of this scenario could be buttons that has the class to be switched on another element (say tabs in a container).