Struggling with manipulating SVGs in JavaScript and looking to extend a line by clicking a button? Check out this code snippet I've included in the head tag:
<script type="text/javascript">
x=135;
y=135;
var container = document.getElementById("svgbox");
var mySvg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
function svg() {
mySvg.setAttribute("version", "1.2");
mySvg.setAttribute("baseProfile", "tiny");
mySvg.setAttribute("height","300px");
mySvg.setAttribute("width","300px");
container.appendChild(mySvg);
}
function line() {
x=x-10;
y=y-10;
var L1 = document.createElementNS("http://www.w3.org/2000/svg", "line");
L1.setAttribute("x1", "100"); L1.setAttribute("y1", "100");
L1.setAttribute("x2", x); L1.setAttribute("y2", y);
L1.setAttribute("stroke", "#05adc7");
L1.setAttribute("stroke-width", "2px");
mySvg.appendChild(L1);
}
</script>
Adding this body text will allow you to interact with the SVG elements:
<body onload="svg()">
<form>
<input type="button" onClick="line()" />
</form>
<div id="svgbox">
</div>
</body>
Encountering an error regarding the null variable "container" when clicking the button? Any ideas where I might be going wrong?