Automatically adjust zoom on focused object within a D3 force layout

I have implemented an autocomplete feature in my force directed graph to highlight selected nodes by coloring them red. Now, I am looking to implement a "zoom" functionality where the window magnifies to 400% the size of the selected node and centers it within the view.

Below are snippets of the relevant code sections: (or you can directly access the jsFiddle demo I created.)

Firstly, here is the code used to create the svg element:

var w = 4000,
    h = 3000;
var vis = d3.select("#mysvg")
    .append("svg:svg")
    .attr("width", "100%")
    .attr("height", "100%")
    .attr("id","svg")
    .attr("pointer-events", "all")
    .attr("viewBox","0 0 "+w+" "+h)
    .attr("perserveAspectRatio","xMinYMid")
    .append('svg:g')
    .call(d3.behavior.zoom().on("zoom", redraw))
    .append('svg:g');

Additionally, here's an example function for redrawing the graph upon normal zoom:

function redraw() {
    trans=d3.event.translate;
    scale=d3.event.scale;
    vis.attr("transform",
        "translate(" + trans + ")"
            + " scale(" + scale + ")");
}

Displayed below are the nodes of the graph:

vis.selectAll("g.node")
    .data(nodes, function(d) {return d.id;})
    .enter().append("g")
    .append("circle")
        .attr("id", function(d){return "circle-node-"+ d.id})
        .attr("fill","white")
        .attr("r","50px")
        .attr("stroke", "black")
        .attr("stroke-width","2px");

Lastly, here's the implementation of the autocomplete feature:

$(function() {
    $( "#tags" ).autocomplete({
        source: nodes; //...
        select: function( event, ui){
            // ...
            vis.selectAll("#circle-node-"+ui.item.value)
                .transition()
                .attr("fill", "red")
        }

    })
}); 

I have provided minimal code snippets to avoid overwhelming with information. Apologies if anything was overlooked.

Update: To see my progress so far, check out this jsFiddle demonstration.

Answer №1

The transformation and moving should be combined in the same function as when you change the color of the node to red. You haven't specified exactly how you want the zoom feature to work, but possibly the simplest approach is to apply translate and scale to the g element that holds the graph.

I have modified your jsfiddle accordingly; see the updated result here. I am assuming that by "400% the size of the node" you mean that the node should be enlarged by 400%? To make it more flexible, I have added a variable for the zoom factor that can be adjusted if needed.

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

Issue with ASP.NET Core Controller not properly receiving complete JavaScript array object from Ajax call

When passing a JavaScript Object Array through ajax to the controller, I noticed that if there are more than 11 objects in the array, the controller receives it as null. However, with 11 or fewer objects, the array is received successfully. Here is an exam ...

Incorporate a binary document into a JSPdf file

I am currently utilizing JsPDF to export HTML content into a downloadable PDF. Explore the following example which involves taking some HTML content and generating a downloaded PDF file using JsPdf import React from "react"; import { render } fro ...

Testing a custom Angular directive that encapsulates the functionality of SlickGrid

Currently, I am working on testing an angular directive that acts as a wrapper for slickgrid. 'use strict'; describe('Unit: Grid Directive', function() { var $scope; var element; beforeEach(module('grid')); beforeEac ...

What is the best way to show an alert() when a user clicks on a marker in Google Maps?

My current setup:view image description ... google.maps.event.addListener(marker,'click',function() { this.map.setZoom(15); this.map.setCenter(marker.getPosition()); console.log('hello world'); this.presentAlert(); // ERROR co ...

Angular 2 - Karma is having trouble locating the external template or style file

The file structure for this project (taken from the Angular 2 official site) is as follows: https://i.stack.imgur.com/A6u58.png Upon starting Karma, I encountered errors indicating that two files were not found under /@angular/... To resolve this issue, ...

"Learn how to easily format specific characters in JavaScript using the text plugin to create bold text strings with a unique

I would like to transform this text into something like "|| something 1 || something 2 || more || last one ||" and then make all of that string bold by adding "|" around it then it would look like this "|| something 1 || something 2 || more || last one | ...

ng-hide is not functioning to display the form

I'm trying to display a form using ng-if when the "add" button is clicked, but it's not working. I've looked at several examples and tried them all, but none have worked for me. Here is the code I am using: angular.module('myFormApp&ap ...

What is the best way to hide my rectangle in HTML?

Just starting out with Wix for my website. I have a block of HTML code that creates a blue rectangle, but I want it to disappear automatically after 30 seconds. What additional code do I need to achieve this effect? Also, is there any unnecessary code I c ...

The input-group-btn is positioned to the right of the field, appearing to float

The input-group-btn for the targetDate field remains fixed on the right side of the input group despite screen width variations until I introduce the automatically generated CSS from the hottowel generator. I require assistance in identifying which aspect ...

Retrieve the route parameters and exhibit the default option in a dropdown menu using Angular 2/4/5, along with translations implemented through ngx-translate

Is there a way to extract route parameters from a URL and then display them in a drop-down menu? I've attempted some solutions using ActivatedRoute, but they are not returning the first value after the base reference. For instance, If the URL is: l ...

Question about sending multiple Axios POST requests with parameters

I'm new to Stack Overflow and seeking help with a specific issue on my Rails backend and Vue.js frontend website. The challenge I'm facing involves making two POST requests simultaneously when the submit button is clicked. My "Trips" controller ...

Update geographic coordinates using Javascript

I am currently developing a Google Maps feature in a Rails 3.2.12 project. My goal is to update the Latitude and Longitude values through the infoWindow for the location created. When a user clicks on a marker on the map, an infoWindow will open displayin ...

Guide to configuring the initial lookAt/target for a Control

I'm looking to establish the initial 'lookAt' point for my scene, which will serve as both the center of the screen and the rotation control's focus. Ideally, I'd like to set a specific point or object position rather than rotation ...

Include the script tags retrieved from an array

I'm exploring the idea of dynamically adding JavaScript to the DOM using an array and a loop. The goal is to load each script sequentially, starting with scripts[0], then scripts[1], and so on. var myScripts = [["external", "https://code.jquery.com/j ...

Utilize Sequelize to enclose a column with double quotation marks in a where clause

I am working with a JSONB column in my database. My goal is to make a query to the database where I can check if a specific value in this JSON is true or false: SELECT * FROM table WHERE ("json_column"->'data'->>'data2')::boo ...

Learn how to dynamically populate text fields with data when an option is selected from a dropdown menu that is populated from a database using Laravel and Ajax technologies

Basically, I've included a drop-down menu in my form that retrieves values from the database. The form itself contains input fields, some of which already have values saved in the database. I'm using the drop-down menu to automatically load these ...

Maintaining the highlight of the active row in Oracle Apex Classic Report even after the dialog window is closed

Greetings to everyone gathered here! Currently, I am working on a single page in Oracle Apex (version 4.2.6.00.03) that contains two Classic Reports — one serving as the "master" report and the other displaying the corresponding "details". Additionally, ...

Guidelines for sending data as an array of objects in React

Just starting out with React and I have a question about handling multi select form data. When I select multiple options in my form, I want to send it as an array of objects instead of an array of arrays of objects. Can anyone help me achieve this? import ...

Guide to developing a reusable component or partial in react.js

My first experience with React.js involved a relatively simple task. I started by creating an app.js file that loads the initial page, containing my navigation menu and rendering the children props. However, I realized that instead of keeping the navigat ...

Adjust the Container's gutters in MaterialUI according to screen sizes

I am trying to adjust the gutters for different screen sizes in my project. I want to turn off the gutters for xs, sm, and md, but have them enabled at xl and larger. Despite following the API documentation, it doesn't seem to be working as expected. ...