Reputation: 2779
I have a zoom functionality made in D3, but I'd like to make it optional, so I'd like a way to turn it off. Here's my code:
//Zoom command ...
var zoom = d3.behavior.zoom()
.x(xScale)
.y(yScale)
.scaleExtent([1,10])
.on("zoom", zoomTargets);
var SVGbody = SVG.append("g")
.attr("clip-path", "url(#clip)")
.call(zoom);
/
/The function handleling the zoom. Nothing is zoomed automatically, every elemnt must me defined here.
function zoomTargets() {
if($("#enableZoom").is(':checked')){
var translate = zoom.translate(),
scale = zoom.scale();
tx = Math.min(0, Math.max(width * (1 - scale), translate[0]));
ty = Math.min(0, Math.max(height * (1 - scale), translate[1]));
//This line applies the tx and ty which prevents the graphs from moving out of the limits. This means it can't be moved until zoomed in first.
zoom.translate([tx, ty]);
SVG.select(".x.axis").call(xAxis)
.selectAll("text")
.style("text-anchor", "end")
.style("font-size", AXIS_FONTSIZE)
.attr("transform", function(d) {
return "rotate(-30)"
});
SVG.select(".y.axis").call(yAxis)
.selectAll("text")
.style("font-size", AXIS_FONTSIZE);
SVG.selectAll("circle")
.attr("cx", function(d, i){ return xScale(graphDataX[i]);})
.attr("cy",function(d){return yScale(d);});
SVGMedian.selectAll("ellipse")
.attr("cx", function(d, i){ return xScale((i*100)+100);})
.attr("cy", function(d){ return yScale(d-0.01);});
}
}
As you can see I tried using an if-statement to prevent the zoom functionality from working when a checkbox isn't ticked. This prevents users from scrolling on the page when the mouse is inside of the SVG frame.
I'd like the correct way to do this. Thanks very much in advance!
Upvotes: 0
Views: 2634
Reputation: 14591
This is a way to disable d3 zoom behavior
SVGbody.select("g").call(d3.behavior.zoom().on("zoom", null));
Upvotes: 3