holyredbeard
holyredbeard

Reputation: 21218

svg elements created on the fly not to be seen

I've just started out a small project to test animation with svg with jQuery, and has started of by creating rect's dynamically. However, something is wrong in my code below because even if I can see the created svg elements in the Inspector, they're not to be seen in the browser.

Why is it like this and what can I change to make the rect's be seen? I have tried the code in Chrome, Firefox and Safari.

jsFiddle: http://jsfiddle.net/JFACW/

js:

$(document).ready(function() {

    var NR_OF_FLAKES = 100,
               flake = $('.flake'),
                   x = flake.attr('x'),
                   y = flake.attr('y'),
                 svg = $('#svg');

    for(var i = 0; i < NR_OF_FLAKES; i++) {

        var xPos = randomize('width'),
            yPos = randomize('height');

        $('svg').append('<rect class="flake" width="5" height="5" x=' + xPos + ' y=' + yPos + '/>');
    }

    flake.attr('x');

    var height = $(window).height();

    function randomize(direction) {

        if (direction == 'width')
            direction = $(window).width();
        else
            direction = $(window).height();

        var rand = Math.floor((Math.random() * direction) + 1);

        return rand;
    }
});

html:

...
<body>
    <div id="box2">
        <svg id="svg" xmlns="http://www.w3.org/2000/svg" height="1600" version="1.1"></svg>
    </div>
</body>
...

css:

rect.flake {
    fill: rgb(255,205,0);
}

Upvotes: 0

Views: 338

Answers (2)

methodofaction
methodofaction

Reputation: 72405

Just ditch jQuery and go pure javascript:

var NR_OF_FLAKES = 100,
             svg = document.querySelector('svg'),
           xmlns = "http://www.w3.org/2000/svg";

for(var i = 0; i < NR_OF_FLAKES; i++) {

   var xPos = Math.random()*window.innerWidth,
       yPos = Math.random()*window.innerHeight,
      flake = document.createElementNS(xmlns, "rect");

  flake.setAttribute("width", 5);
  flake.setAttribute("height", 5);
  flake.setAttribute("x", xPos);
  flake.setAttribute("y", yPos);
  flake.setAttribute("class", "flake");
  svg.appendChild(flake);
}

http://jsfiddle.net/PAxyx/

Upvotes: 2

Thomas W
Thomas W

Reputation: 15371

This is a duplicate of jquery's append not working with svg element?

SVG doesn't have innerHTML, therefore .append does not work. For further information, see the linked question.

Edit: This might not be the full truth. jQuery seems to append rect elements that are not in the SVG namespace, but they have to be.

Upvotes: 1

Related Questions