Home > Back-end >  How to change the color of section of a SVG on click then change back after clicking elsewhere?
How to change the color of section of a SVG on click then change back after clicking elsewhere?

Time:04-29

I am trying to figure out how to make it so when a user clicks a state on a SVG map of the US (specially this one) the state changes color. In addition when they click on another state or anywhere else, the color of the previous state goes back to the default.

So far I have functions to change the colors, but not sure how to select the specific states themselves.

function ColorChange() {
this.style.fill = "#0A3161";
return false;
}

function RestoreColor() {
this.style.color = "#D3D3D3";
return false;
} 

CodePudding user response:

document.addEventListener('click', function(e) {
    e = e || window.event;
    var target = e.target /* || e.srcElement,
        text = target.textContent || target.innerText*/;   
 
       
 const id = document.getElementById(target.id)
 id.setAttribute("fill","#FF0000")
    
 console.log(target)
});

CodePudding user response:

Key is to save the (previous) clicked object in a sensible location.

<svg viewBox="0 0 200 100">
  <circle cx="50" cy="50" r="45" fill="red" />
  <circle cx="100" cy="50" r="45" fill="green" />
  <circle cx="150" cy="50" r="45" fill="blue" />
</svg>

<script>
  let svg = document.querySelector("svg");
  svg.onclick = (evt) => {
    let previous = svg.previous;
    if (previous) {
        previous.setAttribute("fill", previous.getAttribute("savedfill"));
    }
    let clicked = evt.target;
    clicked.setAttribute("savedfill", clicked.getAttribute("fill"));
    clicked.setAttribute("fill", "gold");
    svg.previous = clicked;
  }
</script>

  • Related