A summary of the issue: Rectangles show up fine, but the text labels don't show up at all, and the mouse behaviors (just fading to different colors) don't work at all. I'm still fairly new to D3JS so it's probably a "noob" question, but I just cannot pick out the issue - though I'm guessing it has to do with what I use to append.
Here is my code:
var w = 1000;
var h = 1000;
var svgBody = d3.select("body").append("svg")
.attr("width", w)
.attr("height", h);
var contributors = [{name: "a", iy: 30},
{name: "b", iy: 60},
{name: "c", iy: 90},
{name: "d", iy: 120}];
var r = svgBody.selectAll(".rect").data(contributors)
.enter()
.append("g")
.attr("class", "rect");
r.append("rect")
.attr("width", 90)
.attr("height", 20)
.style("fill", "#db8215")
.attr("stroke", "black")
.attr("x", 400)
.attr("y", function(d){return d.iy});
//Mouse behaviors
//Mouseover - it turns slightly lighter
r.on("mouseover", function(d){
d3.select(this).select("rect").transition()
.duration(500)
.attr("color", "#e06d08");
});
r.on("mouseout", function(d){
d3.select(this).select("rect").transition()
.duration(500)
.attr("color", "#ffa354");
});
r.append("text")
.attr("text-anchor", "middle")
.attr("x", 400)
.attr("y", function(d){return d.iy})
.style("font-size", "30px")
.style('fill', 'white')
.style('font-family', 'Helvetica')
.text(function(d){return d.name});
There are several posts asking the same questions, but involve different issues. My code doesn't append text directly to the desired shape like this or this or this, and there are no errors that pop up in the console debugger.
All help is much appreciated! Thank you in advance!
Edit: Sorry, it looks like I took an earlier version of the code. I tried appending to the "g" element (after seeing the other posts) AND to the "rect" element (previously).
Update: It turns out the selection (maybe in conjunction with the incorrect appending) did it, as was described in the accepted answer. Thank you so much!