Skip to content Skip to sidebar Skip to footer

Getting An Svg Map To Change Color On Click

I have an SVG map of the world

Solution 1:

You are very close, just need to use syntax like elem.style.fill = colour;

functiondisplayName(elem){
  console.log(elem.id)
}

functiononClickHandler(elem){
  var country_id = elem.idvar colour = "#004400";
  //with selector://var country = document.getElementById(country_id);//country.style.fill = colour;//or simply with elem arg passed into event handler:
  elem.style.fill = colour;
}

//Alternative method to attach events:/*
const allPaths = document.querySelectorAll('svg > path');
allPaths.forEach(elem => elem.addEventListener('click', myFuncHandler));

function myFuncHandler(e){
  var country_id = e.target.id
  var colour = "#004400";
  e.target.style.fill = colour;
}
*/
<svgviewbox="250 250 1250 1000"><pathinkscape:connector-curvature="0"id="Algeria"onmouseover="displayName(this)"onclick="onClickHandler(this)"data-name="Algeria"data-id="DZ"d="m 1021,336.9 -3.6,0.4 -2.2,-1.5 -5.6,0 -4.9,2.6 -2.7,-1 -8.7,0.5 -8.9,1.2 -5,2 -3.4,2.6 -5.7,1.2 -5.1,3.5 2,4.1 0.3,3.9 1.8,6.7 1.4,1.4 -1,2.5 -7,1 -2.5,2.4 -3.1,0.5 -0.3,4.7 -6.3,2.5 -2.1,3.2 -4.4,1.7 -5.4,1 -8.9,4.7 -0.1,7.5 0,0.4 -0.1,1.2 20.3,15.5 18.4,13.9 18.6,13.8 1.3,3 3.4,1.8 2.6,1.1 0.1,4 6.1,-0.6 7.8,-2.8 15.8,-12.5 18.6,-12.2 -2.5,-4 -4.3,-2.9 -2.6,1.2 -2,-3.6 -0.2,-2.7 -3.4,-4.7 2.1,-2.6 -0.5,-4 0.6,-3.5 -0.5,-2.9 0.9,-5.2 -0.4,-3 -1.9,-5.6 -2.6,-11.3 -3.4,-2.6 0,-1.5 -4.5,-3.8 -0.6,-4.8 3.2,-3.6 1.1,-5.3 -1,-6.2 1,-3.3 z"style="fill:#f2f2f2;fill-rule:evenodd" /></svg>

Alternatively, you might want to think about attaching events using this syntax:

const allPaths = document.querySelectorAll('svg > path');

allPaths.forEach(elem => elem.addEventListener('click', myFuncHandler));

Then you don't need to add the prop onclick="onClickHandler(this)" to each path element.

Post a Comment for "Getting An Svg Map To Change Color On Click"