Reputation: 321
I want to highlight every term/word that the user has clicked on with an background box for this particular term/word. I am using the on click function, I can access and set the color of the word itself, but I am not able to set the background of this word. How can I achieve that?
Here is my draw function:
function draw(words) {
d3.select("#interests").append("svg")
.attr("width", w)
.attr("height", h)
.append("g")
.attr("transform", "translate(" + [w >> 1, h >> 1] + ")")
.selectAll("text")
.data(words)
.enter().append("text")
.style("font-size", function(d) { return d.size + "px"; })
.style("font-family", "Impact")
.style("fill", function(d, i) { return fill(i); })
.style("cursor", "pointer")
.attr("text-anchor", "middle")
.attr("transform", function(d) {
return "translate(" + [d.x, d.y] + ")rotate(" + d.rotate + ")";
})
.text(function(d) { return d.text; })
.on("click", function(d) {
// d3.select(this).style("fill");
d3.select(this).style("background","yellow");
if (d.inGraph == true){
d.inGraph = false;
unloadInterest(d.text);
} else {
d.inGraph = true;
loadInterest(d.text, "#ff0000");
}
});
}
Upvotes: 0
Views: 1471
Reputation: 2970
text
elements don't have a background style or attribute. To highlight words you have to create a rect
element with the same size as the text (getBBox()
for dimensions).
Your code can be modified as follows.
function draw(words) {
var main_g = d3.select("#interests").append("svg")
.attr("width", w)
.attr("height", h)
.append("g")
.attr("transform", "translate(" + [w >> 1, h >> 1] + ")")
main_g.selectAll("text")
.data(words)
.enter().append("text")
.style("font-size", function(d) { return d.size + "px"; })
.style("font-family", "Impact")
.style("fill", function(d, i) { return fill(i); })
.style("cursor", "pointer")
.attr("text-anchor", "middle")
.attr("transform", function(d) {
return "translate(" + [d.x, d.y] + ")rotate(" + d.rotate + ")";
})
.text(function(d) { return d.text; })
.on("click", function(d) {
var bbox = this.getBBox();
main_g.insert("rect",":first-child")
.attr("x", bbox.x)
.attr("y", bbox.y)
.attr("width", bbox.width)
.attr("height", bbox.height)
.style("fill", "yellow");
if (d.inGraph == true){
d.inGraph = false;
unloadInterest(d.text);
} else {
d.inGraph = true;
loadInterest(d.text, "#ff0000");
}
});
}
Upvotes: 2