Saturday, February 4, 2023

SVG remove polygon using JS

 In this post, you will find a code snippet that will remove a state polygon on mouse click. The tech stack used are: HTML, CSS, JS and SVG.

The result will look like below image.

First step is to setup a basic HTML page and use the 'object' tag to embed the SVG file into the HTML body like this:-

<object id="svg-object" data="svg_map_filename.svg" type="image/svg+xml"></object>

Then we will update the SVG file with CSS and JS code as follow. In the '.svg' document, we need to put the styles declaration inside cdata, as follows;-

<style type="text/css" media="screen"> <![CDATA[

/*Add CSS code here...*/

  ]]> </style>

The CSS style is added at the top of the svg file just after the opening <svg ...> tag.

Lastly we will add JS code at the end of the  svg file just after the closing <svg ...> tag. The script code must be wrapped inside cdata, as follows;-

<script> <![CDATA[

    // Add JS code here...

  ]]> </script>

Wrapping the CSS or JS codes in the cdata is important so that characters like > don't conflict with XML parsers. Using cdata is highly recommended for embedding style or script in SVG, even if the conflicting character is not given in the style sheet or script file.

That is it!

No comments:

Post a Comment