create svg with jquery

from http://stackoverflow.com/questions/13732326/jquery-created-svg-rect-doesnt-appear

by karlovac

HTML

<h1>Look: SVG!</h1>

<button id="reload">hack!</button>
<button id="redraw">forceRedraw()</button>

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

<div id="chartLocation">

</div>

JavaScript

jQuery("h1").append(" and jQuery!");

const phases = [
  {
    "name": "Page Load/JS Load",
    "start": 0,
    "color": "gold",
    "duration": 518.6999999284744
  },
  {
    "name": "Headless Init",
    "start": 518.6999999284744,
    "color": "limegreen",
    "duration": 1628.3999999761581
  },
  {
    "name": "OLA Download",
    "start": 2147.0999999046326,
    "color": "orchid",
    "duration": 3576.2000000476837
  },
  {
    "name": "OLA Processing",
    "start": 5723.299999952316,
    "color": "mediumpurple",
    "duration": 15
  },
  {
    "name": "UI Initialization",
    "start": 6148.899999976158,
    "color": "lightcoral",
    "duration": 497
  },
  {
    "name": "Load Image",
    "start": 6645.899999976158,
    "color": "lightskyblue",
    "duration": 39
  }
];
var $chart = jQuery("#chart");

const $timeline = $(`<svg id="chart" class="chart" width=1000 height=120 style="display: block;">
</svg>`);

for (let i= 0; i<phases.length; i++) {
	let phase = phases[i];
  const msToPxScale = 10;
  const $bar = $(document.createElementNS("http://www.w3.org/2000/svg", "rect")).attr({
    x: phase.start/msToPxScale,
    y: 0,
    width: phase.duration/msToPxScale,
    height: 50
  });
  $timeline.append($bar);

  $bar.attr({fill: phase.color, stroke: "black"});
}
$('#chartLocation').append($timeline);

jQuery('#reload').click(function() {
    jQuery('body').html(jQuery('body').html());
});


jQuery('#redraw').click(function() {
    $chart[0].forceRedraw();
});