Exploring D3.js version 4: Implementing a zoom button alongside the traditional wheelmouse zoom functionality

This question pertains to the same topic as a previously asked and answered one:

  • D3.js - how to add zoom button with the default wheelmouse zoom behavior

I have attempted to implement the code found in this link http://bl.ocks.org/linssen/7352810.

The reason for seeking help here is that the solutions provided are based on D3.js version 3, which do not effectively address my issue. Below is my current implementation for zooming.

let translateVar = [0,0];
let scaleVar = 1;

function create_pan_zoomable_svg() {
    let svg = d3.select("body")
        .append("svg")
        .attr("width", "100%")
        .attr("height", "100%")
        .style("background-color", "#eeeeee")
        .call(_zoom).on("dblclick.zoom", null)
        .append("g");
    d3.select("#zoom_in").on('click', function() { _zoom.scaleBy(svg, 2)});
    d3.select("#zoom_out").on('click', function() { _zoom.scaleBy(svg, 0.5)});

    return svg;
}

var _zoom = d3.zoom()
    .on("zoom", function() {
        translateVar[0] = d3.event.transform.x;
        translateVar[1] = d3.event.transform.y;
        scaleVar = d3.event.transform.k;
        svg.attr('transform', 'translate(' + translateVar[0] + ',' + translateVar[1] + ') scale(' + scaleVar + ')');
    });

In trying to solve my problem, I came across this post d3.js V4 Button Zoom Implementation acting weird. However, adapting the code only resulted in the buttons working but not the wheelmouse-based zoom. Below is the adapted code from that post.

function create_pan_zoomable_svg() {
    let zoom = d3.zoom().on("zoom", zoomed);

    let svg = d3.select("body")
        .append("svg")
        .attr("width", "100%")
        .attr("height", "100%")
        .style("background-color", "#eeeeee")
        .append("g").call(zoom).on("dblclick.zoom", null);

    d3.select("#zoom_in").on("click", function() {
        zoom.scaleBy(svg.transition().duration(750), 1.2);
    });
    d3.select("#zoom_out").on("click", function() {
        zoom.scaleBy(svg.transition().duration(750), 0.8);
    });

    return svg;
}

function zoomed() {
    svg.attr("transform", d3.event.transform);
}

One issue I encountered was that if I were to place the append("g") after calling the zoom, both types of zoom would work but fail to track translation accurately.

To further analyze the problem, please refer to: https://jsfiddle.net/vxhuzyp2/5/

Your assistance in resolving this matter would be greatly appreciated.

Answer №1

Explore the steps involved in handling the ambiguity of naming a variable 'svg' and creating an SVG element.

let zoom = d3.zoom().on("zoom", zoomed);

let svgElement = d3.select("svg")
  .attr("width", "100%")
  .attr("height", "100%")
  .style("background-color", "#eeeeee")
  .call(zoom)
  .on("dblclick.zoom", null);
let g = svgElement.append("g");
//d3.selectAll("#zoom-section i").on("click", zoomClick);
g.append("circle").attr("r", 50).attr("fill", "red");
d3.select("#zoom_in").on("click", function() {
  zoom.scaleBy(svgElement.transition().duration(750), 1.2);
});
d3.select("#zoom_out").on("click", function() {
  zoom.scaleBy(svgElement.transition().duration(750), 0.8);
});

function zoomed() {
    g.attr("transform", d3.event.transform);
}
<svg width="960" height="500"></svg>
<script src="https://d3js.org/d3.v4.min.js"></script>

<button id="zoom_in">+</button>
<button id="zoom_out">-</button>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to enhance a state's capabilities in Machina.js?

When using Machina.js (version 0.3.6), how can I instantiate a modified FSM constructor where both the child and parent FSMs define behaviors in the same states? Here is the code snippet: var _ = require('lodash'); var machina = require('m ...

Using an external npm module in TypeScript can result in the tsc output directory being modified

In my TypeScript project, I have set up the build process to generate JavaScript files in the ./src/ directory. Everything works smoothly when building against existing npm modules, such as Angular 2 imports. However, I encountered a strange issue when I ...

Locate unique values for a specific field in MongoDB documents using Mongoose

Imagine a scenario where there is a Schema named MyDoc with a field called key. Here are the sample documents: [ { "key": 1 }, { "key": 2 }, { "key": 2 }, { "key": 3 }, { "k ...

Issue encountered when attempting to store a nickname in the MySQL database

I am currently working with the Steam API and I have encountered an issue when trying to save user nicknames to the database. The problem occurs when the nickname contains Russian words or special symbols such as ʊ ϟ ღ 回 ₪. The database is set up ...

Angular 4 application coming to a standstill whenever a network request is triggered in Internet Explorer

My app has the ability to make calls and update the screen based on incoming data. However, I have encountered a major issue - the app is extremely slow when using Internet Explorer (I.E), so much so that scrolling is nearly impossible. Surprisingly, the s ...

Anticipate the middleware function to either invoke the next function or return a HTTP 400 status code

I am eager to delve into unit testing and am looking to test my Node API. I am utilizing Express with Typescript and Jest for testing. Prior to invoking the controller middleware, I apply the route input validation middleware to verify the validity of the ...

The script functions perfectly on one page, but encounters issues on another page

I'm currently working on developing an iOS7 WebApp using a template that I came across on this website: After writing some JavaScript/jQuery to create a fading effect for a picture and a toolbar, and testing it successfully on a blank page, I encount ...

Get rid of just this one specific element using jQuery

I have implemented a feature where tasks are dynamically added to a list when the input is entered and its length is less than or equal to 30 characters, followed by clicking a button. Each task comes with a trash icon for removal, sourced from an externa ...

What is the best way to display a notification on the screen when a user fails to select an option from a checkbox in PHP?

I'm currently tackling a form project where I need to trigger an alert if the user hasn't selected any options from a checklist. Despite scouring various resources for solutions, my lack of JavaScript coding skills has left me at a standstill. He ...

a guide on passing variables between Python and HTML

I am currently utilizing d3.js to create a collapsible tree. The json format I receive is transformed by a python script that performs calculations based on database values. The python script begins with the root argument for the tree. From there, I calcu ...

The Inner Workings of JavaScript Objects and Organized Numerical Keys

I've scoured numerous other resources with no luck in finding a satisfactory answer to this query. It's common knowledge that JavaScript objects arrange their integer keys in ascending order, not in the order they were inserted. const lookup = { ...

Using jQuery, transform JSON into an array

After running my PHP code, I have the following result: $result = '[{"MFG_NAME":"ABC","CONCATED_MKT_SHARE":"01-MAR-14|0.59"},{"MFG_NAME":"XYZ","CONCATED_MKT_SHARE":"01-MAR-14|0.87"},{"MFG_NAME":"ABC","CONCATED_MKT_SHARE":"01-APR-14|0.25"},{"MFG_ ...

Trap mistakes while utilizing async/await

Within my Express application, I have a register function for creating new users. This function involves creating the user in Auth0, sending an email, and responding to the client. I am looking to handle errors from Auth0 or Postmark individually and send ...

Getting the ThreeJs OrbitControl import version directly from the CDN

Using threejs from CDN and requiring OrbitControl as well, I encountered an issue with importing both Three and OrbitControl using the latest version 0.148.0: import * as THREE from 'https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__ ...

Checking if a button is visible in PythonFinding out if a button is visible

My task involves verifying the display status of a button element on the UI. The code was written in Java script by a developer, and I am creating automated scripts using Selenium Webdriver and Python. When the button is enabled, a li tag is added to the c ...

md-input container displays content only upon user interaction

Currently, I am working with AngularJs 1 and Angular-Material Design. One issue I encountered was with a md-input container used for file uploading. The problem I faced was that even after selecting a file, it wasn't being displayed in the md-input co ...

Raphael JS meets Java in a cutting-edge web application

I am interested in utilizing the Raphael JavaScript framework to generate charts using live data obtained from my Java web application. Is there a better approach than storing this data in hidden fields within my webpage and then retrieving it in the Rap ...

What sets apart using "!=" from "=" in the Jade template engine when assigning a variable?

I am a beginner in NodeJS and JS, so please excuse me if this question seems simple. Recently, I came across an example in the ExpressJS documentation that showed how to utilize the Jade template engine. The example included the following lines: html h ...

"Encountering problem with Angular HTTP services: the requested URL is not

Attempting to send data to API servers is resulting in a 404 error. Testing it on Postman shows that everything works fine. JSONP is being used for posting data due to cross-domain issues. The console displays the following: GET http://myapi.com/registrat ...

Can someone help me troubleshoot the issue with my submit button's onclick function?

I am currently working on a project where I have a content box enclosed in a div tag. Within this content box, there are paragraphs with unique IDs for individual styling rules. I have set margins, padding, and other styles accordingly. At the bottom of th ...