Search code examples
jquerycssbackground-color

Nicer way to change color of multiple buttons


i used jQuery to change the color of my buttons based on a click event. The code works and is "easy" to read, but i guess pretty horrible, when i will later have 20+Buttons which will also manipulate HTML.

function R1() {
    $("#R1").css("background-color", "red")
  $("#R2").css("background-color", "green")
  $("#R3").css("background-color", "green")
  $("#R4").css("background-color", "green")
  $("#R5").css("background-color", "green")
  }

function R2() {
  $("#R1").css("background-color", "green")
  $("#R2").css("background-color", "red")
  $("#R3").css("background-color", "green")
  $("#R4").css("background-color", "green")
  $("#R5").css("background-color", "green")
  }

function R3() {
  $("#R1").css("background-color", "green")
  $("#R2").css("background-color", "green")
  $("#R3").css("background-color", "red")
  $("#R4").css("background-color", "green")
  $("#R5").css("background-color", "green")
  }
function R4() {
  $("#R1").css("background-color", "green")
  $("#R2").css("background-color", "green")
  $("#R3").css("background-color", "green")
  $("#R4").css("background-color", "red")
  $("#R5").css("background-color", "green")
  }

function R5() {
  $("#R1").css("background-color", "green")
  $("#R2").css("background-color", "green")
  $("#R3").css("background-color", "green")
  $("#R4").css("background-color", "green")
  $("#R5").css("background-color", "red")
  }


document.getElementById("R1").addEventListener("click", R1)
document.getElementById("R2").addEventListener("click", R2)
document.getElementById("R3").addEventListener("click", R3)
document.getElementById("R4").addEventListener("click", R4)
document.getElementById("R5").addEventListener("click", R5)

Can you help me to write that in a good programming style?


Solution

  • As you are using JQuery, you can simply attach the click event to the button and when it is clicked change the background-color to red for this button and set the background-color of other buttons, except this, to green

    $(document).ready(function(){
      $('button').click(function(){
        $(this).css("background", "red").siblings().css("background", "green");
      });
    });
    button {
      background: green;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <button id='R1'>Click R1</button>
    <button id='R2'>Click R2</button>
    <button id='R3'>Click R3</button>
    <button id='R4'>Click R4</button>
    <button id='R5'>Click R5</button>