Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

d3 retrieve and add to current selection's attribute value

Tags:

d3.js

I'm trying to get the values for an element's translation.

For example, if I select the x axis:

d3.select('.x.axis').attr("transform")

then I get

"translate(0,112)"

How do I get the 0 and the 112 without parsing a regexp?

I'm trying to do it so that I can add to the value. In pseudocode:

d3.selectAll('.x.axis').attr('transform', 'translate('
        .attr('transform').match(/(\d+)(\.\d+)?/g)[0] // <-- clearly won't work
        + additional_value
        + ', 0)');
like image 750
ari gold Avatar asked Dec 02 '13 23:12

ari gold


People also ask

What do the select () and selectAll () functions in d3 do?

select selects the first matching element whilst d3. selectAll selects all matching elements. Both functions take a string as its only argument. The string specifies which elements to select and is in the form of a CSS selector string (e.g. div.

What does ATTR do in d3?

attr() function is used to set the attribute of the element that is selected. The name of the attribute and value of the attributes are to be set using this function.

What does d3 selectAll return?

selectAll() function in D3. js is used to select all the element that matches the specified selector string. Parameters: This function accepts single parameter HTML tag as a parameter. Return Value: This function returns the selected elements.


2 Answers

D3 provides the transform() function for exactly this purpose:

var t = d3.transform(d3.select('.x.axis').attr("transform")),
    x = t.translate[0],
    y = t.translate[1];
like image 63
Lars Kotthoff Avatar answered Oct 15 '22 08:10

Lars Kotthoff


if you would like to use selectAll you could try something like this:

// move ticks to the center of the x-axis   
var transform;
d3.selectAll('.tick').attr('transform', function(){
  transform = d3.transform(d3.select(this).attr("transform"));
  return "translate("+transform.translate[0]+", -3)";
});
like image 4
Keith Mitchell Avatar answered Oct 15 '22 10:10

Keith Mitchell