Zoom/Pan with Onclick

433 views
Skip to first unread message

Kyle Foreman

unread,
Aug 7, 2011, 3:19:15 PM8/7/11
to d3...@googlegroups.com
Hello all

I have a world choropleth map that opens up a jquery pop up with more detailed information when a country is clicked. I'd also like to add the zoom behavior with panning to the map. However, because pan uses mousedown, it's also registering as an onclick event and creating the popup. Any ideas on how to prevent panning from triggering the popup? Can I identify whether or not mousemove occurs between mousedown and mouseup and then only trigger onclick when there's no movement?

Thanks for any suggestions!
Kyle

Mike Bostock

unread,
Aug 9, 2011, 4:13:04 PM8/9/11
to d3...@googlegroups.com
The force layout's drag behavior does this, so I imagine you could use
the same technique. And perhaps in the future we could make the zoom
behavior do this automatically.

As you've surmised, you need to track whether a mousemove occurs
between mousedown and mouseup. If a mousemove occurs, you then need to
prevent the click event from firing. The psuedo code is something like
this:

function mousedown() {
dragging = true;
}

function mousemove() {
if (dragging) preventClick = true;
}

function mouseup() {
dragging = false;
}

function click() {
if (preventClick) {
d3.event.stopPropagation();
preventClick = false;
}
}

The other requirement is that your click event listener is capturing,
which means that it takes priority and receives the event before your
normal click listener. (Otherwise, you'd stop propagation after the
popup is triggered, which won't be very helpful.) You can specify a
capturing listener by using the third argument `true` to the `on`
operator: on("click", click, true).

Mike

Kyle Foreman

unread,
Aug 9, 2011, 4:38:56 PM8/9/11
to d3...@googlegroups.com
Thanks Mike! The third operator for on() is what I was missing in my attempt.

Jesus Noland

unread,
Apr 23, 2015, 12:31:18 AM4/23/15
to d3...@googlegroups.com
Has there been any updates to have this functionality added to the Zoom Behavior?

farrelld...@gmail.com

unread,
Apr 23, 2015, 3:56:34 PM4/23/15
to d3...@googlegroups.com
Jesus,

You might want to take a look at https://github.com/emeeks/d3-carto-map.  It has click to pan/zoom built in.

Dean
Reply all
Reply to author
Forward
0 new messages