Move, release and securely anchor a node in D3JS

In my HTML File, I am using D3JS to display graphs. You can find the working example in this link here. I understand that the function below should allow me to fix node positions when dragging and dropping:

var drag = force.drag()
.on("dragstart", dragstart);

function dragstart(d) {
  d3.select(this).classed("fixed", d.fixed = true);
}

Despite implementing this code, I am still unable to lock node positions after dragging them. What I'm looking for can be seen in the functionality demo at this link. How can I modify it so nodes remain fixed in their new position without reverting back?

Answer №1

Check out this example: http://bl.ocks.org/mbostock/3750558

To make it work, remember to include the drag function call:

var drag = force.drag()
    .on("dragstart", dragstart);

This is what the dragstart function looks like:

function dragstart(d) {
  d3.select(this).classed("fixed", d.fixed = true);
}

The crucial part is setting d.fixed to true.

UPDATE

In your demo, you forgot to call node_drag on the nodes. Make sure to do that like this :

 var node = gnodes.append("circle")
      .attr("class", "node")
      .attr("r", 5)
      .style("fill", function(d) { 
        thelistofcolors[d.group] = color(d.group);
        return color(d.group); })
      .call(node_drag); // <<<<<<<this line

Also, adjust the tick function so that you can use it later:

  force.on("tick", tick);

  function tick() {
    link.attr("x1", function(d) { return d.source.x; })
        .attr("y1", function(d) { return d.source.y; })
        .attr("x2", function(d) { return d.target.x; })
        .attr("y2", function(d) { return d.target.y; });

    gnodes.attr("transform", function(d) { 
        return 'translate(' + [d.x, d.y] + ')'; 
    });



  };

Here's the updated demo with all data displayed (not filtered on click) : https://jsfiddle.net/vgy1s8k3/4/

Answer №2

To ensure the proper positioning of nodes during dragging, it is essential to set the 'fixed' node property to true on dragstart.

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="//d3js.org/d3.v3.min.js"></script>
<style>

.node {
  stroke: #fff;
  stroke-width: 1.5px;
}

.link {
  stroke: #999;
  stroke-opacity: .6;
}

</style>
</head>
<body>
<script>

var width = 1280,
      height = 960;

var color = d3.scale.category20();

var force = d3.layout.force()
    .charge(-120)
    .linkDistance(30)
    .size([width, height]);

var svg = d3.select("body").append("svg")
    .attr("width", width)
    .attr("height", height);

d3.json("graph.json", function(error, graph) {
  if (error) throw error;

  force
      .nodes(graph.nodes)
      .links(graph.links)
      .start();

  var link = svg.selectAll("graph.link")
      .data(graph.links)
      .enter().append("line")
      .attr("class", "link")
      .style("stroke-width", function(d) { return Math.sqrt(d.value); });

  var node = svg.selectAll("graph.node")
      .data(graph.nodes)
      .enter().append("circle")
      .attr("class", "node")
      .attr("r", 5)
      .style("fill", function(d) { return color(d.fill); })
      .call(force.drag);

  var drag = force.drag()
    .on("dragstart", dragstart);

    function dragstart(d) {
      d.fixed = true;
    }

  node.append("title")
        .text(function(d) { return d.name });

    force.on("tick", tick);

    function tick() {
      link.attr("x1", function(d) { return d.source.x; })
          .attr("y1", function(d) { return d.source.y; })
          .attr("x2", function(d) { return d.target.x; })
          .attr("y2", function(d) { return d.target.y; });

      node.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; });
    };


});

</script>
</body>
</html>

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

Youngster listens for guardian's occurrence in Angular 2

While the Angular documentation covers how to listen for child events from parents, my situation is actually the opposite. In my application, I have an 'admin.component' that serves as the layout view for the admin page, including elements such a ...

What is the process for accessing npm packages through a website?

Recently, I've been delving into the realm of Node.js and attempting to configure a specific Node.js package created by Uber. Despite my limited experience with Node.js, I rigorously followed these steps: Initiated cloning their repository from here ...

Upon transitioning from typescript to javascript

I attempted to clarify my confusion about TypeScript, but I'm still struggling to explain it well. From my understanding, TypeScript is a strict syntactical superset of JavaScript that enhances our code by allowing us to use different types to define ...

Looking for suggestions on AngularJS and Rails integration!

I'm currently in the process of creating a website using rails, but I want to integrate AngularJS for several reasons: Efficient sorting between 2 different types of data (such as selecting various restaurants from a list and then different food cate ...

Animation of hand-drawn letters using SVG technology

I'm exploring SVG animations and am currently struggling with animating a slogan letter by letter. The font is handwritten and should give the effect of being written with a text marker. Can anyone provide me with some tips on how to approach this cha ...

Ensuring Radiobuttons are Selected on a Page After Clicking the Submit Button

Seeking assistance with this issue: I am working on a page that includes radio buttons: <label>Delivery type:</label> <input type="radio" name="delivery" value="7" class="delivery-item" id="del-type-7" onclick=""><label class="label" ...

In my React application, I have integrated p5 sketches that constantly loop and repeat

Currently facing a challenge integrating p5 sketches into my React App. I've tried adjusting the z Index of the toolbar to place the p5 elements underneath, but they end up repeating instead. Check out the repository here (sketches can be found in the ...

Trouble arises while attempting to establish a connection between nodejs and the mLab database, accompanied by deprecation

I am still a beginner with Node.js and currently using Node version 10.5.0 along with Mongoose version 5.1.7. Despite checking various questions related to mLab, I couldn't find a solution to my specific issue. I am attempting to establish a connectio ...

Is there a way to keep the selected option in handlebar permanently, even after multiple page refreshes?

I am having trouble implementing the drop-down menu option in handlebars using jQuery. Therefore, I have opted to use the select-options menu instead. Here is the code snippet: <select name="sources" id="sources" class="custom-s ...

Angular country selection dropdown featuring national flags

Can anyone help me find an Angular Bootstrap dropdown list of countries with flag icons and country codes? For example: United Kingdom - UK Please take a look at this reference image: https://i.sstatic.net/UEfvW.png I want the dropdown to resemble the o ...

What sets apart a React component from a function-as-component in React?

React is really confusing to me right now. Take this simple react component for example: export default function Foo(){ return( <div> <div>some text</div> </div> ) } I want to add a child compone ...

Dynamic sliding effect in CSS for seamless showing and hiding of div elements

I stumbled upon a fantastic solution in these forums How to create sliding DIV on click? However, what I really wanted was for the content to fade in and out with just a click of a button. Here is the code snippet I am currently working with: <html> ...

Encountering an error: Reading an undefined property - NodeJS, Express, and Mongoose

These are the two functions I have: exports.list = function (req, res){ Material.find(function(err, materials) { res.render('materials/list', {title: 'Pagina Materiali', materials: materials}); }); } exports.modify = function (req ...

The repository's dependencies remain unresolved by Nest

I encountered an error in my nestjs application. Unfortunately, I am having trouble identifying the issue within my code snippet. Here is a glimpse of the relevant sections: AppModule import { Module } from '@nestjs/common'; import { TypeOrmMod ...

When an event is triggered in Angular Component, the object is not properly defined in the handler causing errors

While experimenting with createjs and angular, I encountered an issue when trying to update my stage after an image loads. It seems like there might be a problem related to Angular in this situation. Upon completion of the load event on the Bitmap object a ...

Unable to clear input code as intended

After using the code I found here, it seemed to work as expected. However, when implemented on my page, everything worked except for the cursor not changing when hovering over the 'x' button. Surprisingly, the cursor only changed when the input b ...

Struggling to load app.css, main.js, and other files while using an Express server

I'm struggling with my code setup. Essentially, I have the following piece of code: var express = require('express'); var app = express(); var server = require('http').Server(app); app.get('/', function(req,res){ res.s ...

Is there a way in Javascript or JQuery to determine if a function is currently executing, or is there a way to tap into a return event?

Let me paint a picture of a common scenario: there's a form with numerous inputs (around 60-70). Each input must undergo validation, and if it is invalid, the form returns false. To prevent multiple AJAX requests with visual feedback, I need to safegu ...

Reliable Dropdown Navigation Bars

Once I have successfully implemented three dynamic drop down menus using the combination of jQuery, AJAX, and PHP, the next challenge arises. After populating the dropdown menus based on user selections (e.g., selecting a value in the first dropdown menu ...

Create a new document and verify its presence within the system

Is there a way to save a text file (.txt) to my computer's local disk and prompt the user to scan a document before looping until it finds a specific PDF file on the disk? EDIT: I've heard about HTML5's FILE API in JavaScript, which seems ...