csiz
csiz

Reputation: 5180

Using d3 drag, why doesn't dragstart have d3.event.x set?

I can access d3.event.x from inside on("drag"...) but x doesn't exist inside on("dragstart"...); why? And how can I get it another way, preferably not very hackish?

Check console output for this example:

d3.select("body").append("svg").append("rect")
    .attr("width", 100)
    .attr("height", 100)
    .style("color", "black")
    .call(
        d3.behavior.drag()
            .on("dragstart", function(){
                console.log(d3.event);
            })
            .on("drag", function(){
                console.log(d3.event);
            })
            .on("dragend", function(){
                console.log(d3.event);
            })
        );

JSFiddle

Upvotes: 1

Views: 2504

Answers (2)

Mark
Mark

Reputation: 108522

@Lars explains why, so how do you do it? d3.mouse is pretty slick:

    d3.behavior.drag()
        .on("dragstart", function(){
            console.log('relative to rect: ' + d3.mouse(this));
            console.log('relative to body: ' + d3.mouse(d3.select("body").node()));
        })

Updated example.

Upvotes: 2

Lars Kotthoff
Lars Kotthoff

Reputation: 109232

This is the intended behaviour (see the documentation):

Drag events (but not dragstart and dragend events) expose "x" and "y" properties representing the current position of the drag gesture in local coordinates.

The start and end events are fired before and after the actual drag takes place, i.e. there's no coordinate change compared to the first and last drag events.

Upvotes: 2

Related Questions