Drag behavior returning NaN in D3
d3.js, javascript, svg
Solution
This is because `d3.event` relay to data, if you check in your code that:
.attr("x", function(d,i){console.log(d);return points[i]})
you will find that d is text, which can't have x,y properties.
the solution is to make each letter as object (you also splitted them by "," but i gues it should be "" ) so here the code:
var stage = d3.select("body").append("svg");
var points = [0, 50, 100, 150];
var letters = "drag".split("").map(function(d, i) {
return {
text: d,
x: points[i],
y: 100
}
});
var log = d3.select("#log");
//drag behaviour, will bind later
var drag = d3.behavior
.drag()
.origin(Object)
.on("drag", dragmove);
//append texts
var texts = stage
.selectAll("text")
.data(letters)
.enter()
.append("text")
.attr("font-family", "Arial")
.attr("class", "word")
.attr("x", function(d, i) {
return d.x;
})
.attr("y", 100)
.text(function(d) {
return d.text;
})
.call(drag);
function dragmove(d) {
log.text(
"x: " + d3.event.x + ", " +
"y: " + d3.event.y + ", " +
"dx: " + d3.event.dx + ", " +
"dy: " + d3.event.dy);
//set new position to the object
d.x=d3.event.x;
d3.select(this).attr("x", d3.event.x);
}
and fiddle
Problem
I have this code: ``` var stage = d3.select("body").append("svg"); var points = [0, 50, 100, 150]; var letters = "drag".split(","); var log = d3.select("#log"); //drag behaviour, will bind later var drag = d3.behavior.drag() .origin(Object) .on("drag", dragmove); //append texts var texts = stage .selectAll("text") .data(letters) .enter() .append("text") .attr("font-family", "Arial") .attr("class", "word") .attr("x", function(d,i){return points[i]}) .attr("y", 100) .text(function(d){return d}) .call(drag); function dragmove() { log.text( "x: " + d3.event.x + ", " + "y: " + d3.event.y + ", " + "dx: " + d3.event.dx + ", " + "dy: " + d3.event.dy ); d3.select(this).attr("x", d3.event.x); } ``` However, `d3.event.x` and `d3.event.y` are returning `NaN`. Funnily enough, `d3.event.dx` and `d3.event.dy` are returning the right values. What is wrong with my code? You can see a jsfiddle here: http://jsfiddle.net/UMwmr/