Search code examples
javascriptcsssvg

How to make checkbox show/hide SVG-Content


i have rectangles and lines in SVG together with a checkbox. I want somehow to make a checked checkbox to show the content and when its checked, otherwise not. So for example: When the checkbox for "areas" are checked the "area rectangles" will be shown and the same for the "river-lines".

It does not seem very hard but I'm totally new to JavaScript and cant find a way to make it work.

The script is to be in HTML and be able to be shown on a web browser. Everything is visible but i cant get the check boxes to work.

I have tried to build functions with "onClick" and to change the color to "none".

<html>
    <head>
        <title>Web Mapping using SVG</title>
        <script>
        </script>
        <style>
        </style>
    </head>

    <body>
        <form>
            <fieldset style="width:600px; height:600px">
                <legend>Layers</legend>
                <input type="checkbox" id="areaCbx" /><strong id="areaTXT">Area</strong><br>
                <input type="checkbox" id="riverCbx" /><strong id="riverTXT">River</strong><br>
                <hr />

                <svg width="100%" height="100%">
                    <g id="AreaSVG" >
                        <rect x="0" y="0" width="100" height="200" />
                        <rect x="120" y="0" width="100" height="200" />
                        <rect x="280" y="0" width="100" height="200" />
                        <rect x="400" y="0" width="100" height="200" />
                        <rect x="0" y="260" width="100" height="200" />
                        <rect x="120" y="260" width="100" height="200" />
                        <rect x="240" y="260" width="100" height="200" />
                        <rect x="360" y="260" width="100" height="200" />
                    </g>
                    <g id="RiverSVG">
                        <line x1="0" y1="230" x2="500" y2="230" style="stroke:blue;stroke-width:6" />
                        <line x1="250" y1="230" x2="250" y2="0" style="stroke:blue;stroke-width:6" />
                        <line x1="0" y1="500" x2="500" y2="500" style="stroke:blue;stroke-width:6" />
                    </g>
                </svg>
            </fieldset>
        </form>
    </body>
</html>


Solution

  • So seems you just want to show/hide parts of SVG depending on which checkbox checked? if so:

    <style>
        svg #AreaSVG,
        svg #RiverSVG { display: none; }
        #areaCbx:checked ~ svg #AreaSVG { display: block; }
        #riverCbx:checked ~ svg #RiverSVG { display: block; }
    <style>