javascript - d3 - when setAttribute() works but .attr doesn't? -
i'm puzzled why d3 method setting element attribute fails (in piece of code) while traditional js method works. (i'm trying update chloropleth colours user clicks html button change data being plotted, same json.)
the html simple:
<div id="buttons"> <button id="party">parties</button> <button id="tenure">tenure</button> </div>
here's relevant js 2 lines side-by-side. when run in chrome, "object # has no method 'attr'":
var paths = svg.selectall("path"); var plot = { "mode": "party", "redraw": function() { var e = e || window.event; var targ = e.target || e.srcelement; if (targ.nodetype == 3) targ = targ.parentnode; switch (targ.id) { case "party": // code in here break; case "tenure": paths.each(function(d,i) { this.setattribute("class",""); // same question here if (d.in_office_full_date) {
// line errors:
this.attr("style", "fill: " + t_scale(getjsdatefromexcel(d.in_office_full_date).getfullyear()));
// ... line works:
this.setattribute("style", "fill: " + t_scale(getjsdatefromexcel(d.in_office_full_date).getfullyear())); } else this.setattribute("style", "fill: #111"); // neutral colour }); break; default: console.log("unknown event trigger in redraw()"); } } } var t_scale = d3.scale.linear() .domain([1973,2013]) .range(['red','white']); d3.select("body").selectall("#buttons button") .on("click",plot.redraw);
i hope can help!
the issue way you're calling methods of this
within each(function(d, i) { ... })
.
you're in right direction: this
refers plain html element you're modifying. attr
function expect call method of d3 selection –– not of html element. hence, need wrap this
in d3 selection:
paths.each(function(d,i) { d3.select(this) .attr("class",""); });
calling setattribute
worked because it's method of plain html element, d3's attr
more robust.
but having said that, more idiomatic way achieve you're doing this:
paths .attr("class", "") .style("fill", function(d, i) { if (d.in_office_full_date) { return t_scale(getjsdatefromexcel(d.in_office_full_date).getfullyear()); } return "#111"; });
Comments
Post a Comment