Skip to content

How to toggle different colors on consecutive clicks (on SVG objects)

I’m trying to let all elements in group change to specific colors on different amount of clicks. One click = red, two clicks = blue, etc. It needs to toggle all children in the group.

JavaScript

function call1() {
    console.log('call1');
    const children = document.getElementById('btn1').children;
    $(document).ready(function(){
        $("btn1").toggle(
            function(){$("btn1").css({"fill": "red"});},
            function(){$("btn1").css({"fill": "blue"});},
            function(){$("btn1").css({"fill": "green"});
        });
    });
}

SVG file

<g id="btn1" onclick="call1()">
    <polygon fill="#FF0013" points="366.699,131 410,56 453.301,131  "/>
    <polygon fill="#07FF00" points="323.699,656 367,581 410.301,656     "/>
    <polygon fill="#0000FF" points="409.699,656 453,581 496.301,656     "/>
    <polygon points="366.699,581 410,656 453.301,581    "/>
</g>

I want all the elements in the SVG group to change colors on the first click to red, second click to green, and third click to blue.

Answer

You could use a modulus and switch statement to cycle through each colour:

var count = 0;

function call1() {
  const button = $("#btn1");
  console.log(count);
  count = count % 3 + 1;
  switch (count) {
    case 1:
      button.css("fill", "red");
      break;
    case 2:
      button.css("fill", "blue");
      break;
    case 3:
      button.css("fill", "green");
      break;
  }
}

Example:

var count = 0;

function call1() {
  const children = $("#btn1").children();
  count = count % 3 + 1;
  switch (count) {
    case 1:
      children.css("fill", "red");
      break;
    case 2:
      children.css("fill", "blue");
      break;
    case 3:
      children.css("fill", "green");
      break;
  }
}
<svg height="1000" width="100%">
  <g id="btn1" onclick="call1()">
    <polygon fill="#FF0013" points="366.699,131 410,56 453.301,131  "/>
    <polygon fill="#07FF00" points="323.699,656 367,581 410.301,656     "/>
    <polygon fill="#0000FF" points="409.699,656 453,581 496.301,656     "/>
    <polygon points="366.699,581 410,656 453.301,581    "/>
  </g>
</svg>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>