Tutorial on d3.selection vs. nodes vs. DOM elem
by Nivaldo
HTML
<!--
Three entities are passed via the accessor functions, function(d) {...}
1) d as the value of the node object (__data__)
2) i as the index of the node object (__data__)
3) this as the DOM element (text, circle, rect, etc.)
-->
JavaScript
var dataset = [
{"name":"mary","action":"goes"},
{"name":"john","action":"comes"}
];
var svg = d3.select("body").append("svg");
//console.log(svg);
var text = svg.selectAll('text')
.data(dataset)
.enter()
.append('text')
.attr('x',0)
// NOTE: *d* here is the node object, not a d3.selection object
.attr('y',function(d,i) {console.log(d); return (i + 1) * 20;})
.text(function(d) {return d.name + " " + d.action;})
.style("fill","red")
.style("stroke-width",0.5)
.style("stroke","blue")
// these are all equivalent ways of setting a DOM element style
//.style("font-size", "26px")
//.style("font-size", function() {return "26px";})
// the next two methods are silly since a d3.selection is already adorned with styling functions, such as style() (and attr() for setting attributes, etc.)
// NOTE: *this* inside here is the DOM element only, not a d3.selection item
.style("font-size", function() {console.log(this); return this.style.fontSize="26px";})
//.style("font-size", function() {return d3.select(this).style.fontSize="26px";})
// here is a way of setting a DOM element style based on node data
.style("font-size", function(d) {return d.name == "mary" ? "26px" : "12px";})
.on('mouseover',mouseover)
.on('mouseout',mouseout);
/*console.log(text);*/
function mouseover() {
// NOTE: *this* here is the DOM element only, JUST LIKE IT IS inside the accessor function, function(d) {...}
console.log(this);
console.log(d3.select(this));
// now we turn this into a d3.selection!!!
d3.select(this).style("opacity", 0);
};
function mouseout() {
d3.select(this).style("opacity", 1);
};