spanishgum
spanishgum

Reputation: 1052

How can I access current size properties of a d3 svg chart in Javascript?

I've made a responsive layout with bootstrap for 2 columns, and my left column has a d3 force-layout chart.

Previously I was using a fixed size, and with it was calculating a constant used by another function to ensure nodes have sensible placement on the chart (a solution I found here on stack):

var w = 400,
    h = 400,
    r = 6,
    k = Math.sqrt(nodes.length / (w * h)),
    fill = d3.scale.category20();

var force = d3.layout.force()
    .gravity(100 * k).charge(-10 / k)
    .linkDistance(30)
    .nodes(nodes).links(links)
    .start();

Now that I have a responsive layout, I can't use w and h. Rather I need some some sort of getter to see the current width and height of the chart so I can calculate my constant.

I'm new to Javascript code so this is the best I came up with by exploring the console:

d3.select("#chart").property('height')['animVal']['value']
d3.select("#chart").property('width')['animVal']['value']

Is this how I should be doing this? Is there a more direct function? This seems ugly to me..

Upvotes: 0

Views: 201

Answers (1)

jobB
jobB

Reputation: 441

This depends on the rest of your code, but typically, you would use getBoundingClientRect(). This function returns a read only object containing the location and the width and the height of the selected element. In your case, you could use it like this:

d3.select("#chart").getBoundingClientRect().height
d3.select("#chart").getBoundingClientRect().width

Upvotes: 1

Related Questions