Reputation: 79
How can I change the colour of my node? If I click on a node that was previously blue, it should change colour, e.g. to purple. But if I now click on another node, this node should become purple and the previously clicked node should get an old colour (i.e. become blue again). how do I do this?
const color = d3.scaleLinear().domain([0, 1]).range(["#03fc90", "#03dbfc"]);
var node = svg.append("g")
.attr("class", "nodes")
.selectAll("circle")
.data(dataset.nodes)
.enter()
.append("circle")
.attr("r", 5)
.style("fill", function(d,i) {
return color(i);})
.on("click", (evt, currentNode) => {
d3.select(this).
.style.color=’purple’
});
Upvotes: 1
Views: 740
Reputation: 7230
fill
style for every node.const nodes = [
{id: 1, x: 50, y: 50},
{id: 2, x: 50, y: 100},
{id: 3, x: 100, y: 75},
];
const svg = d3.select('svg');
svg.selectAll('circle.node')
.data(nodes, d => d.id)
.enter()
.append('circle')
.classed('node', true)
.attr('cx', d => d.x)
.attr('cy', d => d.y)
.attr('r', 20)
.style('fill', 'blue')
.style('cursor', 'pointer')
.on('click', onClickNode);
function onClickNode (e, d) {
svg.selectAll('.node.selected')
.classed('selected', false)
.style('fill', 'blue');
d3.select(this)
.classed('selected', true)
.style('fill', 'purple');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/6.7.0/d3.min.js"></script>
<svg />
Upvotes: 2