Search code examples
javascriptd3.jstouchmouse

Need d3 brush to NOT work on touch devices


I'm implementing d3's brush behavior based on Mike Bostock's code here.
jsfiddle version

I'd like brush to work only with mouse events and NOT with touch events. I tried this:

function brushended() {
    if (d3.event.sourceEvent && d3.event.sourceEvent.type != "mouseup") return; 
    // Code for zooming
    // ...
}

Touch now creates the brush rectangle but doesn't do anything further. So, my objective is half-achieved. This is what I'd like to have: on touch devices, brush should be completely ignored and touch should perform its default behavior (e.g. touchmove for scrolling, two-finger for zooming).


Solution

  • Add a filter for your brush:

    var brush = d3.brush().filter(() => event instanceof MouseEvent).on("end", brushended)
    

    This will only activate the brush for MouseEvent and ignore TouchEvent