webmonkey237 webmonkey237 - 4 months ago 10
jQuery Question

jQuery: Changing one class with multiple buttons

I am simply trying to change a background color on a div using multiple buttons, the code I have come up with so far works but just keeps on adding more classes to the .eaStaff container div rather than toggling them, I tryed originally using .attr but I need to keep the class .eaStaff, using .attr removed/replaced that class.

FIDDLE

//BG COLOUR
$('.bg a').click(function (e) {
e.preventDefault();
console.log('dd', $(this).data('class'))
$('.eaStaff').toggleClass($(this).data('class'));
});

Joe Joe
Answer

Toggle class either removes or adds a specific class to an element, it doesn't clear other classes. Instead you can remove the other classes before adding that class.

$('.eaStaff').removeClass('transBG darkBg lightBg');
$('.eaStaff').addClass($(this).data('class'));

https://jsfiddle.net/p34r7m87/5/