Reputation: 15303
When user click on the legend
i am hiding and showing the path
. it works. But as well i would like to keep the legend
as semi-transparent, when the path
was hidden.
for that, I am trying to add the style to the legend
using the this
key word but it's not working.
what is the correct way to do this? her is my code :
legends.on('click', function(d, i) {
var path = d3.select("#" + d.name);
var visibility = path.style('opacity');
path.style("opacity", visibility == 1 ? 0 : 1);
if (!visibility) {
d3.select(this).style('opacity', 0.5);//not working!
this.style('opacity', 0.5);//not working!
}
});
update
tried this way still not works:
legends.forEach(function(group) {
var legend = group;
legend.on('click', function(d, i) { //throws error
var path = d3.select("#" + d.name);
var visibility = path.style('opacity');
path.style("opacity", visibility == 1 ? 0 : 1);
console.log(legend);
});
})
update
Upvotes: 2
Views: 4402
Reputation: 3004
As per my understanding you want to add click event to legends group.
You should add click event when you are appending the elements. I am adding example with dummy data. Here is filddle. Hope this helps you.
HTML
<div id="chartArea"></div>
CSS
svg {
background-color: #fff;
}
Javscritpt
//appending svg to div and adding width and height
var svg = d3.select("#chartArea").append("svg");
svg.attr({
'width' : 350,
'height': 150
});
//dummy data
var data = [{name: "legend1"}, {name: "legend2"}];
//appending group
var groupSelection = svg.append('g');
//appending legends
var legendSelection = groupSelection.selectAll('text')
.data(data)
.enter()
.append('text')
.attr("x", 10)
.attr("y", function(d, i) { return (i+1) * 15;})
.text(function(d) {return d.name;})
.on('click', legendClickFunction);
//click event handler
function legendClickFunction(d, i) {
console.log(this);
//adding color to text using this selection
d3.select(this).attr("fill", "red");
}
Upvotes: 1