Search code examples
javascriptd3.jsstyles

D3 on("click", toggle


Two of my nodes representing power supply objects. I added an .on("click"..) event on the power-plug node, which changes the colour from green to red. I want to switch the colour from the battery node to green as soon as the power-plug is red. I struggle with a proper toggle function so far.

enter image description here

enter image description here

function toggleColor() {
if (!toggle) {
    d3.select(this).style("fill", "red")
    toggle = true
} else if (toggle) {
    d3.select(this).style("fill", "lightgreen")
    toggle = false
}

}

// set node attributes for node:usv
node
    .filter((d) => {
        return (d.name == "usv")
    })
    .style("fill", "yellow")

// set node attributes for node:power-plug
node
    .filter((d) => {
        return (d.name == "power-plug")
    })
    .style("fill", "lightgreen")
    .on("click", toggleColor)

I just can´t get the connection working as I am using (this) as a pointer. Any idea?


Solution

  • I managed. My filter query was faulty.

    function toggleColor() {
    if (!toggle) {
        d3.select(this).style("fill", "red")
        d3.selectAll("circle")
            .filter(function(d) {
                return d.name == "usv"
            }).style("fill", "lightgreen")
        toggle = true           
    } else if (toggle) {
        d3.select(this).style("fill", "lightgreen")
        d3.selectAll("circle")
            .filter(function(d) {
                return d.name == "usv"
            }).style("fill", "yellow")
        toggle = false
    }
    

    }