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?
Hmmm, a very basic solution I can think for this is to store the last applied class in a variable, then remove that before applying the new class. Something along this line:
var lastBg = "";
$('.boxedBgSwitch').on('click', function (e) {
e.preventDefault();
var bgClass = $(this).data("id");
$('body').removeClass(lastBg).addClass(bgClass);
lastBg = bgClass;
});
Can't say this is the best solution, but it seems to work reliably, and won't break even if you start changing up class names. Here's a JSFiddle to demonstrate it in action. Hope this helps! Let me know if you have any questions.