D3js Using An Attribute That Is Updated Within The Same Callback
As part of a larger project, I'm wanting to update an attribute of an SVG line from within a click handler and then subsequently use that attribute while still within the callback.
Solution 1:
The 'val'
you're setting via the attr
function becomes an attribute of the <line>
element –– not of the model d
that is bound to it. So d.val
is undefined
, which is why the stroke is unaffected.
So you need to get that attribute value from the <line>
element itself. To get hold of that element from inside that function (the one you're using to set stroke-width
), you need to call d3.select(this)
, which creates a d3 selection containing that element (which is this
inside that function).
Then to get its val
attribute, you need to call attr('val')
on that d3 selection. When you call attr
with a single, string param it acts as a getter, rather than a setter, so it'll return the 10
you set on it.
Putting it all together, it looks like this:
.attr("stroke-width", function(d) { return d3.select(this).attr('val'); });
Post a Comment for "D3js Using An Attribute That Is Updated Within The Same Callback"