SVG Map Layers Hover
by Darko
HTML
<div id="state-hovered-is">
</div>
<div id="states" onmousemove="showCoords()">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 961.38 830.7" onClick="getCoords()">
<defs>
<style>
.cls-1 {
fill: #fff;
}
.cls-2 {
fill: #b8c4e6;
}
.cls-3 {
fill: #ce8080;
}
.cls-4 {
fill: #e99bd2;
}
.cls-5 {
fill: #acac90;
}
.cls-6 {
fill: #e6c0c0;
}
.cls-7 {
fill: #4d6ac1;
}
.cls-8 {
fill: #c9e6b8;
}
.cls-9 {
fill: #f3f3db;
}
.cls-10 {
fill: #cece71;
}
.cls-11 {
fill: #7188ce;
}
.cls-12 {
fill: #daa0a0;
}
.cls-13 {
fill: #91916b;
}
.cls-14 {
fill: #dada94;
}
.cls-15 {
fill: #916b86;
}
</style>
</defs>
<title>Canada</title>
<g id="Layer_1">
<ellipse class="cls-1" cx="480.69" cy="415.35" rx="679.8" ry="587.39" />
<path class="cls-1" d="M539.84,220.75c-2.45,5-6.57,8.18-10.72,11.7l2-9.56C534.53,224.17,537,221.84,539.84,220.75Z" transform="translate(-0.06 -0.26)" />
<path class="cls-1" d="M53,543.56c-1.09,2.13-2.18,4.23-3.52,6.84l-.51-10.68.56-.25Z" transform="translate(-0.06 -0.26)" />
<path class="cls-1" d="M771.19,558.14c-.32-2.18-.77-4.36-.89-6.56a3.15,3.15,0,0,1,1.31-2.05,1.76,1.76,0,0,1,1.64.49,4.19,4.19,0,0,1,.17,2.5c-.48,1.84-1.18,3.62-1.79,5.43Z" transform="translate(-0.06 -0.26)" />
<path class="cls-1" d="M40.77,527.77l-7-8.41.35-.18A76,76,0,0,1,40.4,524c.77.71.87,2.14,1.27,3.25Z" transform="translate(-0.06 -0.26)" />
<path class="cls-1" d="M493.56,95.47l3.41,6L485.7,105a30.91,30.91,0,0,1,2.81-2.42C491.7,100.51,493.64,100.2,493.56,95.47Z" transform="translate(-0.06 -0.26)" />
</g>
<g...
CSS
body {
background-color: #fff;
font-family: Arial, Helvetica, sans-serif;
color: #333;
}
g.hover {
opacity: 0.5;
}
#states {
margin: 0 auto;
width: 400px;
max-width: 100%;
}
#state-hovered-is {
text-align: center;
height: 50px;
}
JavaScript
let x = 0;
let y = 0;
function showCoords() {
x = event.clientX;
y = event.clientY;
}
let svgCountry = document.querySelector("#states svg");
let svgStates = svgCountry.querySelectorAll("[data-name]");
let resContainer = document.getElementById("state-hovered-is");
// clear everything
function clearAllOn() {
svgStates.forEach(function(el) {
el.classList.remove("hover");
resContainer.innerHTML = "";
console.clear();
});
}
// display current state in div
function displayState(el) {
var res = el.getAttribute("data-name");
el.classList.add("hover");
resContainer.innerHTML = "You're at" + " " + res;
console.log(res);
}
svgStates.forEach(function(el) {
// mouse events
el.addEventListener("mouseenter", function() {
displayState(el);
});
el.addEventListener("mouseleave", function() {
clearAllOn();
});
// touch events
el.addEventListener("touchstart", function() {
removeAllOn();
addOnFromState(el);
});
});