itailitai itailitai - 5 months ago 12
CSS Question

Svg and buttons

I have this SVG of the world map:

http://codepen.io/itailitai/pen/ZOpJWJ

and this CSS:

.worldmap {

margin: 0 auto;
background-color:#091e2e;

}


I was wondering, Can I make the circles filled with white a button?

Answer

Firstly, you can greatly - and I mean greatly - simplify your SVG by using the <circle> element, eg.

<circle cx="20" cy="20" r="8" />

It's worth doing this because the cubic-bezier paths that you currently have (presumably generated by your editor) are not accurate circles - you cannot represent a circle as a bezier curve for the same reason you can't represent it as a polygon, it would need infinite sides/curves.

Now that your SVG is about a thousand times smaller, you can actually work with it. Your browser can too, as it will load and render many, many times faster now that it doesn't need to calculate thousands of bezier curves.

SVG elements are... elements! This means that JavaScript and CSS can work with them.

I've made a very crude demo here, the important bits being:

[fill=white] {
    cursor: pointer;
}
var white = document.querySelectorAll("[fill=white]");
var l = white.length, i;
for( i=0; i<l; i++) {
 white[i].onclick = function() {alert(this.id);};
}

This very basic code gives the "pointer" cursor to the white circles, and alerts their ID when you click on them.

Depending on your needs, you can build on this however you like.