0

I am having a problem with dragging a group of elements with d3.js, First I load a external svg file with the following code:

    function loadSVG(file) {
        d3.xml(file, "image/svg+xml", function(xml) {
            document.body.appendChild(xml.documentElement)

            d3.selectAll("g").call(drag).data([{ x: 0, y: 0 }]).enter();

        })
    }

As you can see I also set a drag behavior on it with a x and y data which will be used in the dragMove function. This so that the drag will be smooth without it jumping around when it starts.

As you can see in the following piece of code I try to access the data (x&y) in the dragMove method:

    function dragMove(d) {
        d.x += d3.event.dx;
        d.y += d3.event.dy;
        d3.select(this).attr("transform", "translate(" + d.x + "," + d.y + ")");
    }

However when I try this code I get the following error in my console:

Uncaught TypeError: Cannot read property 'x' of undefined 

My guess is that something went wrong with adding the x and y data to the svg group itself. I tried all kind of different way to achieve this but I keep failing. Here is the full script a.t.m.

    var drag = d3.behavior.drag()
        .on("dragstart", dragStart)
        .on("drag", dragMove)
        .on("dragend", dropHandler);

    //loads a svg file and add it to the body
    function loadSVG(file) {
        d3.xml(file, "image/svg+xml", function(xml) {
            document.body.appendChild(xml.documentElement)

            d3.selectAll("g").call(drag).data([{ x: 50, y: 50 }]).enter();

        })
    }

    loadSVG("images/layers.svg");

    function dragStart(d) {
    }

    function dragMove(d) {
        d.x += d3.event.dx;
        d.y += d3.event.dy;
        d3.select(this).attr("transform", "translate(" + d.x + "," + d.y + ")");
    }

    function dropHandler(d) {
        // alert('dropped');
    }

I got a bit of the info to make this from the following 2 links: How to drag an svg group using d3.js drag behavior? https://github.com/mbostock/d3/wiki/Selections#data

Community
  • 1
  • 1
Dirk-Jan
  • 1,109
  • 10
  • 21
  • Your code works fine for me. Could it be a problem with the SVG file? – bloodyKnuckles May 28 '14 at 18:25
  • I hope not, it's a svg file which I am not allowed to change (it is made with a application we have to use, which adds special attributes to it which we have to parse). I will however check it with a clean svg file and see if I get the same error. Thanks for your feedback! – Dirk-Jan May 28 '14 at 18:31

0 Answers0