0

I have a multiple buttons that need to change class on-click. I've managed to piece together some working code but wondering if there's a more efficient way of doing this? Open to all languages and solutions.

Also, is there any benefit of wrapping the (document).ready around the (document).on?

$(document).ready(function() {
  $(document).on('click', '.a', function() {
    $('.a').addClass('b');
    $('.a').removeClass('a');
  });
  $(document).on('click', '.b', function() {
    $('.b').addClass('c');
    $('.b').removeClass('b');
  });
});
div {
  width: 60%;
  padding: 10px 20px;
}

.a {
  background: #bbb;
}

.b {
  background: orange;
}

.c {
  background: lightblue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="a">a</div>
<br>
<div class="a">a</div>
Barmar
  • 741,623
  • 53
  • 500
  • 612
Lowis
  • 123
  • 1
  • 10
  • 1
    This is the standard way to handle dynamic class changes in jQuery. – Barmar Apr 26 '22 at 15:58
  • 1
    You don't need to use `document.ready()` if you're delegating from `document`. But often delegation should be done from a more specific container element, and then you need to wait for the document to be ready. – Barmar Apr 26 '22 at 15:58
  • 1
    Are you trying to change the class of all buttons with a given class or just the specific button that was clicked? – Musa Apr 26 '22 at 16:05
  • If I click an .a class button that will change ALL .a class buttons to .b. And so on .b changes all .b to .c. – Lowis Apr 26 '22 at 16:08
  • 1
    While your code is succinct if you just want to go a->b->c [stop], you *can* use a single event handler to loop through classes, something like: https://jsfiddle.net/op64ga0m/1/ This will allow you to change the array of classes, without needing to rewrite the code / easily add new "steps". eg (compare with first link) https://jsfiddle.net/op64ga0m/2/ – freedomn-m Apr 26 '22 at 16:11

0 Answers0