I realize this has been asked before, but the answer in jquery's append not working with svg element?
doesn't seem to be working in my case. I attempted to do the second answer since it seems to be widely accepted as working.
My goal is go append a svg progress circle to every div element with a circlechart class. I thought that if I made a function that renders the html as a string, then it would be a sufficient workaround, but that doesn't seem to work.
How can I use jQuery to dynamically add a svg element to a page?
function makesvg(){
var svg = $("<svg/>")
.addClass("circle-chart")
.attr("viewbox", "0 0 33.83098862 33.83098862")
.attr("xmlns", "http://www.w3.org/2000/svg");
var background = $("<circle/>")
.addClass("circle-chart__background")
.attr("cx", "16.9")
.attr("cy", "16.9")
.attr("r", "15.9");
var circle = $("<circle/>")
.addClass("circle-chart__circle",
"success-stroke")
.attr("cx", "16.9")
.attr("cy", "16.9")
.attr("r", "15.9")
.attr("stroke-dasharray", "100,100");
var g = $("<g/>")
.addClass("circle-chart__info")
.append(
$("<text/>")
.addClass("circle-chart__percent")
.attr("x", "17.9")
.attr("y", "15.5")
.text("100%")
);
return svg.append(background, circle, g).html()
}
/*
var svg = '<svg class="circle-chart" viewbox="0 0 33.83098862 33.83098862" xmlns="http://www.w3.org/2000/svg">'
+ '<circle class="circle-chart__background" cx="16.9" cy="16.9" r="15.9" />'
+ '<circle class="circle-chart__circle success-stroke" stroke-dasharray="100,100" cx="16.9" cy="16.9" r="15.9" />'
+ '<g class="circle-chart__info">'
+ ' <text class="circle-chart__percent" x="17.9" y="15.5">100%</text>'
+ ' </g>'
+ '</svg>'; */
(function( $ ) {
$.fn.circlechart = function() {
this.each(function() {
$( this ).html(makesvg());
$(this).html(this.html());
});
return this;
};
}( jQuery ));
$('.circlechart').circlechart();
Here's my almost functional CodePen: https://codepen.io/killia15/pen/xYVERv
It works if I just use a string, but not if I use the function.