Search code examples
javascriptuser-interfaced3.jszooming

Changing zoom in D3.js from mousewheel to control+mousewheel


From this question I know how to disable mousewheel zoom in D3.js. How can I remap it to holding control button down plus mousewheel? Thanks.


Solution

  • I found a solution that does not need to modify the D3.js source.

    I based my solution on this question: How to temporarily disable the zooming in d3.js

    Instead of clicking on a button to enable/disable zooming, I used keydown/keyup events:

    svg.call(zoom = d3.behavior.zoom().on('zoom', redrawOnZoom)).on('dblclick.zoom', null);
    
    var zooming = false;
    
    function redrawOnZoom() {
      if (zooming) {
        svgContainer.attr('transform', 'translate(' + zoom.translate() + ')' + ' scale(' + zoom.scale() + ')');
      }
    };
    
    d3.select("body").on("keydown", function () {
        zooming = d3.event.ctrlKey;
    });
    
    d3.select("body").on("keyup", function () {
         zooming = false;
    });
    

    Here is a complete fiddle: https://jsfiddle.net/tabacof/dcbor8eL/3/