Executing the D3.JS function during the 'load' event instead of a mouse event

I am attempting to customize the D3 sankey example provided at this link:

http://bl.ocks.org/d3noob/c2637e28b79fb3bfea13

My goal is to adjust the vertical position of each node to a specific location (in this case, 300px).

One approach I have thought of to achieve this modification is to repurpose the dragmove() function to execute after all SVG elements have been added. In this process, I have modified the d.y value in order to shift it to 300px:

function dragmove(d) {
    d3.select(this).attr("transform", 
        "translate(" + d.x + "," + (
                d.y = 300
            ) + ")");
    sankey.relayout();
    link.attr("d", path);
}

This function is triggered during the addition of nodes:

var node = svg.append("g").selectAll(".node")
      .data(graph.nodes)
    .enter().append("g")
      .attr("class", "node")
      .attr("transform", function(d) { 
      return "translate(" + d.x + "," + d.y + ")"; })
    .call(d3.behavior.drag()
      .origin(function(d) { return d; })
      .on("dragstart", function() { 
      this.parentNode.appendChild(this); })
      .on("drag", dragmove));

Currently, the shifting to 300px occurs as intended upon the specified mouse event, but my objective is for it to automatically shift after all SVG elements have been added.

Simply employing .call() without the mouse event does not produce the desired outcome.

I have also experimented with integrating the shift directly in var node:

return "translate(" + d.x + "," + 300 + ")"; })

However, this results in a misalignment between the links and the nodes, and invoking sankey.relayout() does not seem to resolve this discrepancy.

Answer №1

Discovered the solution!

To resolve the issue, I eliminated the .call() at the conclusion of var node, as the drag event is unnecessary:

var node = svg.append("g").selectAll(".node")
      .data(graph.nodes)
    .enter().append("g")
      .attr("class", "node")
      .attr("transform", function(d) { 
      return "translate(" + d.x + "," + d.y + ")"; });

Next, I assigned a value of 300 to d.y for an arbitrary location:

return "translate(" + d.x + "," + (d.y = 300) + ")"; });

Lastly, I manually triggered the re-drawing of connecting links immediately after defining var node.

sankey.relayout();
link.attr("d", path);

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

Removing a parameter from a link in Vue.js: A step-by-step guide

I currently have the following list of URLs: http://example.com/post?st=1&plt=123&number=1 http://example.com/post?st=1&plt=[exp]&number=1 http://example.com/post/view/12?ex=1&plt=123 http://example.com/post/edit/12?ex=1&tes ...

The stroke width varies unpredictably for outliers within the react-boxplot component

I've been working with the react-boxplot module and I'm trying to customize my outliers to look like a ring as shown in this image Below is the code snippet I have been using: <Boxplot width={boxplotWidth} height={20} ...

Error encountered when executing the npm run dev script

Attempting to follow a tutorial, I keep encountering an error related to the script. I've tried restarting the tutorial to ensure I didn't overlook anything, but the same issue persists. Working on a Mac using pycharm. In the tutorial (from Ude ...

What steps should I take to create a slider using my image gallery?

I have a unique photo gallery setup that I'm struggling with: As I keep adding photos, the cards in my gallery get smaller and smaller! What I really want is to show only 4 photos at a time and hide the rest, creating a sliding effect. I attempted ad ...

Refresh OAuth tokens in AngularJS or JavaScript applications: A step-by-step guide

I am new to the Oauth protocol and have developed an identity server application that generates access_tokens for applications. The lifespan of a token is currently set at 5 minutes. I'm storing the access_token in a cookie when a user logs into my A ...

Is there a way to retrieve the values of a checkbox from a location outside the form where it is initially defined?

After successfully developing a script that deletes rows from a table when a checkbox is selected, I encountered an issue where the values of the checkboxes were not accessible outside of the form action they were placed in. The checkboxes and correspondin ...

Using the data of multiple locations within a for loop to create Leaflet markers for use in a click event

I am currently working on a leaflet map that showcases markers for the top cities in a selected country. The locationList array consists of objects with city information such as latitude, longitude, and cityName. These values are utilized to place markers ...

What is the best way to collapse all expansion panels at once?

I need to close my expansion panel automatically when I click on the Update button. https://i.sstatic.net/pYEYo.png Is there a way to achieve this programmatically? This is the content of my update() function: update(index) { console.log("index&q ...

Detecting the presence of a file on a local PC using JavaScript

In the process of creating a Django web application, I am exploring methods to determine if a particular application is installed on the user's local machine. One idea I have considered is checking for the existence of a specific folder, such as C:&bs ...

Registering components globally in Vue using the <script> tag allows for seamless integration

I'm currently diving into Vue and am interested in incorporating vue-tabs into my project. The guidelines for globally "installing" it are as follows: //in your app.js or a similar file // import Vue from 'vue'; // Already available imp ...

Issue with AngularJs app in IE11: Error message "Object does not have 'then' method"

Encountering an error in IE that says: "TypeError: Object doesn't support property or method 'then'", while trying to execute the following function within my AngularJs controller: GetUserAccessService.checkForValidHashPeriod() .then(fu ...

Below is the JavaScript and AJAX code I've written to successfully transmit a JSON object

After clicking the submit button, the sendJSON function will run to send data from input fields to the server as a JSON object. The input field can have various types such as username, email, radio buttons, checkboxes, text areas, etc. Text inputs work pe ...

How can you determine the number of identical objects within an array using Javascript?

Below is a JSON object that stores the ID and type of each object: let jsonData = [ {"id": "1", "object": "pen"}, {"id": "4", "object": "bag"}, {"id": " ...

Verify whether the items within the ng-repeat directive already contain the specified value

I am facing an issue with displaying a JSON string of questions and answers in ng-repeat. The problem is that I want to display each question only once, but show all the multiple answers within ng-repeat. {Answer:"White",AnswerID:967,answer_type:"RADIO",f ...

I attempted to publish my React application using gh-pages and encountered the following error: "The argument for 'file' must be a string. However, it was received as undefined."

I encountered an issue while attempting to deploy my React application with gh-pages. The error message I'm facing states: "The 'file' argument must be of type string. Received type undefined." Initially, I suspected that the problem was wi ...

Fixing bug in a script that involves identifying steps using Material Steppers

I am currently developing a small AngularJS application that utilizes Material Steppers for navigation. In order to achieve a specific functionality, I need to ensure that items selected from two different sections of the page belong to category ID 1. The ...

Implementing a dynamic function with jQuery Tokenize's change event

I'm currently facing an issue with triggering the on change event on the select box from jQuery Tokenize. Below is the code snippet I am working with: <select id="tokenize" multiple="multiple" class="tokenize-sample"> <option value="1"&g ...

What could be causing my fetch() function to send a JSON body that is empty?

I've been struggling with sending JSON data using fetch as the backend keeps receiving an empty object. In my Client JS code, I have the following: const user = "company1"; const username = "muneeb"; const data = {user, username}; fetch("http://127. ...

jQuery alert displaying outdated information instead of the latest information

I'm facing an issue with a jQuery pop-up functionality. I have content that loads via Ajax, and I want this content to display as a pop-up message when a link is clicked. The first time I click the pop-up link, the correct content is shown. However, a ...

Transforming a string into an array containing objects

Can you help me understand how to transform a string into an array of objects? let str = `<%-found%>`; let result = []; JSON.parse(`["${str}"]`.replace(/},{/g, `}","{`)).forEach((e) => ...