I am having a very interesting issue, where when I add new SVG elements to a div, only the first time the append is called does a new svg element show up. They work when hard coded, but when they are added onmousedown, they don't show up, even though they are added to the HTML file. I am assuming that it is a problem of my understanding of SVG, and that elements can't be added dynamically, but I have been looking around the internet, and can't find anything on the subject.
You can see that on the $(document).mousedown function, a new circle is appended to the svg holder, however even though it is added to the SVG holder, it will not show up on the web page.
CODE:
HTML:
<div id="svgHolder">
<!--THIS CIRCLE SHOWS UP-->
<svg><circle cx='50' cy='50' r='40' stroke='black' stroke-width='1' fill='red' /></svg>
</div>
JQuery/JavaScript:
$(document).ready(function(){
var mouse={
x:0,
y:0,
drawing:false,
lastX:0,
lastY:0,
}
$(document).mousedown(function(e){
console.log('md')
mouse.x=e.clientX
mouse.y=e.clientY
mouse.drawing=true
//THIS CIRCLE WILL BE ADDED TO THE SVGHOLDER, BUT WILL NOT SHOW UP
$("#svgHolder").append("<svg><circle cx='"+mouse.x+"' cy='"+mouse.y+"' r='40' stroke='black' stroke-width='1' fill='red' /></svg>");
});
$(document).mouseup(function(e){
console.log('mu')
mouse.x=e.clientX
mouse.y=e.clientY
mouse.drawing=false
});
$(document).mousemove(function(e){
console.log('mm')
mouse.x=e.clientX
mouse.y=e.clientY
});
});
I think that when you dynamically create a
svg
node you have to create the namespace.Your
svg
is being inserted but out of your viewport so you can't see it, add somewidth
andheight
to thesvg
and also set a proper value forcx
andcy
properties, i.e.Also remember
clientX
andclientY
gives the coordinates relative to the viewport in CSS pixels.Example1, Example2 and more about SVG.