Jake
Jake

Reputation: 5

Javascripts don't work with SVG

The code below should generate 100 random rectangles. But its not working. Can anyone tell me what I am doing wrong??

<html>
<head>
<script type="text/javascript">
function rectan()
{
var svgns = "http://www.w3.org/2000/svg";
for (var i = 0; i < 100; i++) {
    var x = Math.random() * 5000,
        y = Math.random() * 3000;

    var rect = document.createElementNS(svgns, 'rect');
    rect.setAttributeNS(null, 'x', x);
    rect.setAttributeNS(null, 'y', y);
    rect.setAttributeNS(null, 'height', '50');
    rect.setAttributeNS(null, 'width', '50');
    rect.setAttributeNS(null, 'fill', '#'+Math.round(0xffffff * Math.random()).toString(16));
    document.getElementById('svgOne').appendChild(rect);
}
}
</script>
</head>
<body onload="rectan"();">

<svg id="svgOne" xmlns="http://www.w3.org/2000/svg" width="5000" height="3000"> 
            <rect x="50" y="50"
            width="50" height="50"
            fill="black" 
            />
</svg>
</body>
</html>

All it does is one black rectangle form SVG section. I know that I made a mistake somewhere, but I don't know where.

Upvotes: 0

Views: 147

Answers (1)

Robert Longson
Robert Longson

Reputation: 124229

There seems to be an extraneous double qouote in the onload attribute. You want this...

<body onload="rectan();">

Upvotes: 2

Related Questions