Len
Len

Reputation: 123

JavaScript / SVG

I want to get 4 buttons in javascript to change the colour of the square in svg when clicking on them

So far I have the following code

<html>
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN"
"http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd">
<svg width="100%"height="100%"version="1.1"
<svg xmlns="http://www.adobe.com/svg">
  <script type="text/ecmascript">
    <![CDATA[

function chooseColor1() {

document.getElementsById("mySqaure")[0].style.color = "green";


        }

        function chooseColor2() {

            document.getElementsById("mySqaure")[0].style.color = "pink";

        }

        function chooseColor3() {

            document.getElementsById("mySqaure")[0].style.color = "purple";

        }

        function chooseColor4() {

            document.getElementsById("mySqaure")[0].style.color = "blue";

        }



    ]]>
 </script>
 `<g
    id="firstGroup">
    <rect id = "mySquare" x="0" y="0" width="20" height="20"  fill="grey" stroke="black" stroke-width="2" />

  </g>

    <form onsubmit="return false">
       <input type="button" value="green" onclick="chooseColor1()"/>
        <input type="button" value="pink" onclick="chooseColor2()"/>
         <input type="button" value="purple" onclick="chooseColor3()"/>
          <input type="button" value="blue" onclick="chooseColor4()"/>
    </form>
</svg>

</html>

Upvotes: 0

Views: 414

Answers (1)

Andrew Squires
Andrew Squires

Reputation: 31

The reason your button functions aren't working is likely to be due to a misspelling. In your functions you're referring to an element with id "mySqaure" but your element's id is actually "mySquare".

I'm not sure why the buttons aren't appearing as the tags look well-formed, but you do appear to have a "`" character just before the g tag (not sure if this crept in when you copied the code into this page).

Edit: Your first SVG tag isn't closed properly (doesn't have /> at the end).

Upvotes: 1

Related Questions