0

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);
}
holyredbeard
  • 19,619
  • 32
  • 105
  • 171

2 Answers2

2

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/

methodofaction
  • 70,885
  • 21
  • 151
  • 164
1

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.

Community
  • 1
  • 1
Thomas W
  • 14,757
  • 6
  • 48
  • 67
  • 1
    Yes, that should be the problem, by the way to create svg on the fly I recommend to OP the cool Raphael svg library http://raphaeljs.com. – Nelson Nov 30 '12 at 23:39