1

I'm trying to create an SVG bar graph using jQuery AND NO OTHER LIBRARIES but when I create my rectangles they don't show up in the browser although identical ones typed into the html do show up.

var data = [4, 8, 15, 16, 23, 42];
var chart = jQuery("#chart");
jQuery.each(data, function(index, value) {
    var bar = jQuery("<rect/>");
    chart.append(bar);
    bar.attr("y", index * 20)
        .attr("width", value * 10)
        .attr("height", 20);
});

and the html:

<svg id="chart" class="chart" width=420 height=120 style="display: block;">
    <rect y="0" width="40" height="20"></rect> <!--added to test-->
</svg>

The rect tag typed in appears just fine and using the developer tools in Chrome it appears identical to the first one produced by my code but the code generated ones won't show up.

user1301877
  • 125
  • 1
  • 2
  • 10
  • Did my answer work for you? – Magicmarkker Dec 06 '12 at 16:54
  • You can try my jQuery hack: http://stackoverflow.com/questions/11792754/create-and-access-svg-tag-with-jquery/14985470#14985470 – Ruben Kazumov Feb 20 '13 at 17:00
  • Did you ever find out why your created rectangle was not appearing? I'm having the same problem with js generated rectangles not showing up but looking identical in the elements viewer to hand-written rect elements that do appear. – drdozer Mar 24 '14 at 00:50

2 Answers2

7
$(document).ready(function() {
    var data = [4, 8, 15, 16, 23, 42];
    var chart = jQuery("#chart2");
    jQuery.each(data, function(index, value) {
        var bar = $(document.createElementNS("http://www.w3.org/2000/svg", "rect")).attr({
            x: 0,
            y: index * 20,
            width: value * 10,
            height: 20,
            stroke: "red",
            fill: "white"
        });
        chart.append(bar);
    });
});​

http://jsfiddle.net/26ybf/

Edit: Obviously you can remove the stroke and fill attributes, I just had it in there to make sure it was working correctly. Cheers!

Magicmarkker
  • 1,063
  • 7
  • 25
  • Yes! I was doubtful, but apparently jQuery creates wrong element types without using document.createElementNS to "really" create an element. – Loren Oct 30 '16 at 20:08
1

Try to refresh your element:

jQuery.each(data, function(index, value) {
    ...
}    
chart.html(function(){return this.innerHTML});

SEE jsFiddle

A. Wolff
  • 74,033
  • 9
  • 94
  • 155