TAGS :Viewed: 6 - Published at: a few seconds ago

[ Jquery: create dynamic SVG lines ]

I'm trying to create a dynamic SVG overlay over an iframe in my application. The line elements within my SVG need to be dynamically set. The function works and does add the SVG element to the page, but the lines within it do not show. When I use the inspector it says the line height / width is both 0px.

Normal html appears to work which leads me to a problem in my script?

 _createGridOverlay: function () {
    var svg = $('<svg>').attr({id: 'ppGrid', xmlns: "http://www.w3.org/2000/svg", "xmlns:xlink": "http://www.w3.org/1999/xlink"});
    var ll = $('<line>').attr({x1: 500, y1: 0, x2: 500, y2: 500}).css({"stroke": "#000", "stroke-width": "2px"});
    var rl = $('<line>').attr({x1: "1000", y1: "0", x2: "1000", y2: "1000"}).css({"stroke": "#000", "stroke-width": "2px"});

Answer 1

There are some problem with using jquery with svg.

My best suggestion is to use javascript and not jquery for manipulating svg.

Like the attr() jquery attribute makes all attributes lowercase. When using a viewBox <- this gets rewritten as viewbox and does not have any effect on the scg document.

$(document).ready(function() {
  /*var svg = $('<svg>').attr({
    id: 'ppGrid',
    xmlns: "http://www.w3.org/2000/svg",
    "xmlns:xlink": "http://www.w3.org/1999/xlink"

  var NS = "http://www.w3.org/2000/svg";
  var svg = document.createElementNS(NS, "svg");
    id: 'ppGrid',
    "xmlns:xlink": "http://www.w3.org/1999/xlink",

  svg.setAttribute("viewBox", "0 0 1000 1000");

  var ll = document.createElementNS(NS, "line")
    x1: 500,
    y1: 0,
    x2: 500,
    y2: 500
    "stroke": "blue",
    "stroke-width": "15px"
  var rl = document.createElementNS(NS, "line")
    x1: "1000",
    y1: "0",
    x2: "1000",
    y2: "1000"
    "stroke": "#000",
    "stroke-width": "2px"
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>