The nodes.attr() function is invalid within the D3 Force Layout Tick Fn

I'm currently experimenting with the D3 Force Layout, and I've hit a roadblock when it comes to adding elements and restarting the calculation.

Every time I try, I keep encountering this error:

Uncaught TypeError: network.nodes.attr is not a function

Below is the code snippet causing the issue:

var topoConfig = {
  width: 600,
  height: 600
};

var network = {
  nodes: [],
  links: []
}

var tickFn = () => {
  network.nodes
    .attr("cx", function(d) { return d.x; })
    .attr("cy", function(d) { return d.y; });
  network.links
    .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; });
};

var svg = d3.select("body")
  .append('svg')
  .style('width', topoConfig.width + 'px')
  .style('height', topoConfig.height + 'px');

var force = d3.layout.force()
  .nodes(network.nodes)
  .links(network.links)
  .charge(-400)
  .linkDistance(80)
  .size([topoConfig.width, topoConfig.height])
  .on('tick', tickFn);

function reload(){
  var nodes = svg.selectAll('.node')
   .data(network.nodes, d => d.id);

  nodes.enter()
   .append('rect')
   .attr({
      width: 10,
      height: 10,
      x: function(d){return d.x},
      y: function(d){return d.y}
   });

   force.start();
}

function addNode(node){
  network.nodes.push(node);
  reload();
}

window.setTimeout(function(){
  addNode({
    "id": "fabric:a",
    "label": "Fabric Switch",
    "type": "fabric-switch",
    "x": 100,
    "y": 100
  });
}, 500)

If you want to check out the live example on JsFiddle, here's the link: https://jsfiddle.net/teone/wo2gv3ge/3/

Any suggestions on what could be going wrong in my implementation?

Thank you!

Answer №1

As previously mentioned by Lars in the comment, the attr method is accessible within d3 selections rather than JavaScript arrays.

Therefore, you must modify your tick function in the following manner:

var tickFn = () => {
  svg.selectAll('.node') //Where node represents the class name of node elements.
    .attr("x", function(d) { return d.x; })
    .attr("y", function(d) { return d.y; });
  svg.selectAll('.link') //Where link denotes the class name of link elements.
    .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; });
};

Please Note: If you are using rect to represent nodes, ensure that you update the attributes for x and y instead of cx and cy. (Utilize cx and cy attributes if the nodes are circle elements)

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

navigate to the subsequent array element by clicking in JavaScript

My apologies if my explanation is unclear or if the code seems complicated, I'm still in the learning process. I am attempting to showcase data that is stored in an array. The objective is to have this data displayed upon clicking a button and then sh ...

What are the steps to integrating D3js into a WordPress website?

After installing Wordpress and the d3js plugin, I'm looking for the most effective way to upload data in order to create and display graphs on my website. Should I directly upload csv files? And if so, where should I store them? If I prefer storing ...

The target element is out of reach for the Puppeteer selector

When trying to extract the source of multiple images, I encountered an issue with the selectors not working properly. It seems like the elements are fake or not actually present on the page. Every page contains one of the desired elements (the main image) ...

jQuery struggles to locate the active class within the Bootstrap slider

Want to make some changes to the Bootstrap slider? Here is the HTML Code and jQuery: <div id="carousel-slider2" class="carousel slide bs-docs-carousel-example"> <ol class="carousel-indicators"> & ...

When the only source is available, the image undergoes a transformation

Is there a way to dynamically adjust the height of an image using JQuery or JavaScript, but only when the image source is not empty? Currently, I have an image element with a fixed height, and even when there is no source for it, Chrome still reserves sp ...

Is Webpack CLI causing issues when trying to run it on a .ts file without giving any error

I am facing an issue with my webpack.config.js file that has a default entrypoint specified. Here is the snippet of the configuration: module.exports = { entry: { main: path.resolve('./src/main.ts'), }, module: { rules: [ { ...

To activate the speech synthesis feature with a message, you must click a button for it to work

The issue with the code snippet below is that the function "window.speechSynthesis.speak(msg)" does not produce any sound output unless the button is clicked first. Only after clicking the button, the "Hello" message works as intended. Any attempts to call ...

The Gusser Game does not refresh the page upon reaching Game Over

Hi there, I am a beginner in the world of JavaScript and currently working on developing a small guessing game app. However, I have encountered an issue where the page is not reloading after the game is over and the 'Play Again' button appears to ...

When using the `array.join` method with nested arrays, it does not automatically include spaces in the output

function convertArrayToString(arr) { // Your solution goes here. let str = arr.join(", "); return str; } const nestedValues = [5, 6, [7], ["8", ["9", ["10" ]]]]; const convertedString = convertArrayToString(nestedValues); console.log(convertedString ...

What is the reason that .bin/www is recognized as a JavaScript file even though it does not have the .js extension when utilizing express-generator

Can you explain why .bin/www is recognized as a JavaScript file by express-generator even without the .js extension? Whenever I create a bin/ folder with a www file inside, it's automatically identified as a JavaScript file despite the missing .js ex ...

Struggling to retrieve a particular user using ExpressJs due to an error

Looking to retrieve a specific user in ExpressJS from a JSON file. Encountering this error message: UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client This is the snippet of code being u ...

Tips for Showing Certain Slides When the Page Loads

When using jQuery filter effects to organize div slides on a page, I encountered an issue where all the divs containing different slides are displayed on page load instead of just the default chosen ['active'] div. The filter effect itself is fun ...

Refresh Angular component upon navigation

I have set up routes for my module: const routes: Routes = [ { path: ":level1/:level2/:level3", component: CategoriesComponent }, { path: ":level1/:level2", component: CategoriesComponent}, { path: ":level1", component: ...

What steps are required to insert additional tags into select2?

I've successfully retrieved the tags from my API, but I'm facing an issue with adding new tags. Here's the code snippet I've been using: $(function(){ var user_email = localStorage.getItem('email'); var api = ...

MANDATORY activation of CONFIRMATION

Hello everyone, I'm seeking assistance with my code. Below is the form code I need help with: <form action="input.php" method="POST"> <input type="text" class="input" name="firstname" placeholder="First Name" required> <input t ...

What measures does Redux take to ensure race conditions do not occur?

Recently, I delved into Redux and grasped the concept very well. However, there is one particular line in the official documentation that puzzled me: Because all changes are centralized and happen one by one in a strict order, there are no subtle race ...

Determining the minimum and maximum values of a grid using props in a React component

I have created a code for a customizable grid screen that is functioning perfectly. However, I am facing an issue where I want the minimum and maximum size of the grid to be 16 x 100. Currently, when a button is clicked, a prompt window appears asking for ...

Executing a function when a webpage loads in Javascript

I have created a responsive website using Twitter Bootstrap. On my site, I have a video displayed in a modal that automatically plays when a button is clicked. Instead of triggering the function with a button click, I want the function to be called when ...

Using functions as properties in React.js

I am facing an issue while trying to pass a function as a prop. Although I have done this successfully in the past, now I am getting an error (this.props.functionName is not a function). I have a child component called Navbar and a parent component named ...

Modifying Selectize Ajax data in real-time

How can the student_id be changed each time the modal is opened? This is the code: $('#relationshipModal input[name=existing_user]').selectize({ valueField: 'id', searchField: 'name', options: [], create: fal ...