Reputation: 55
I have an svg file (a world map) with paths that shape every single country, which themselves are grouped in g elements which represent the continents - structured like this:
<svg id="worldmap" viewBox="100 0 8334 4171">
<g id="Asia" class="wm-cont">
<path id="AF" d="M5707.92,1390.83l-22.5, etc...
...
I would like to zoom in on a continent once it's clicked, so I wrote the following jQuery for Asia:
$(document).ready(function() {
$("#Asia").click(function() {
// hide all continents
$(".wm-cont").css("display", "none");
// show Asia
$("g.wm-cont#Asia").fadeIn();
// shift the continent into view
$("g.wm-cont#Asia").setAttribute("transform", "translate(-400,439) scale(0.032,-0.032");
});
});
... but I click and nothing happens. Why not? I tried altering my selectors to g#Asia and similar ones, but nothing changed.
Any help with this would be very much appreciated.
For some reason, now this worked:
$(document).on('click', '#Asia', function() {
alert("Asia");
});
... although I didn't change anything in the structure of the svg. Any idea about why this works is warmly welcome :-)
Upvotes: 3
Views: 1843
Reputation: 17600
A g
element is just an empty container; it can not fire events by itself.
put rect
in your g
and try
<rect x="0" y="0" width="100" fill= "white" height="100"></rect>
example demo
document.querySelector("#Asia").addEventListener("click", () => alert("clicked"))
<svg width="300" height="300">
<g id="Asia">
<rect x="0" y="0" width="100" fill= "gray" height="100"></rect>
</g>
</svg>
Upvotes: 3