Simple jquery click toggle function here, though due to my limited knowledge and experience I'm in need of some direction.
I have a set of buttons with a shared boxedBgSwitch
class that each have have a uniquie data-id
. I'd like to assign the data-id
as a class to the body
of my document on click, and only one class should be assigned at a time. The below code works for assigning the classes, but it doesn't remove the previously added classes before adding the new one. What is the recommended way to do this?
jQuery
$('.boxedBgSwitch').on('click', function(e){
e.preventDefault();
var bgClass = $(this).data("id");
$('body').toggleClass(bgClass);
});
HTML
<button data-id="bg-blue" class="boxedBgSwitch color-box"></button>
<button data-id="bg-yellow" class="boxedBgSwitch color-box"></button>
<button data-id="bg-red" class="boxedBgSwitch color-box"></button>
<button data-id="bg-orange" class="boxedBgSwitch color-box"></button>
<button data-id="bg-green" class="boxedBgSwitch color-box"></button>
Obviously, I'm new to jQuery... seems there should be an addOrRemoveClass
method for this very purpose. Perhaps there's an equivalent?