Maddy Chavda
Maddy Chavda

Reputation: 591

Dynamically change background color of node in force directed graph

I was implementing search functionality in force directed graph. Search will be based on node id. When i enter node id in input text box the key-up event will occur. I am able to find node in object but i have no idea how to change background color of searched node in graph and increase the radius of circle. The purpose of assigning the background color to highlight the node in graph. My example link is jsfiddle

this.searchNode = function (id) {
        var searchedNode = findNode(id);
        if(searchedNode == null){
            alert("Not Found");
            return false;
        }else {
            alert("Found");
            update(searchedNode);
        }   
    }

Can anyone suggest me how to do that?

Upvotes: 0

Views: 808

Answers (2)

FernOfTheAndes
FernOfTheAndes

Reputation: 5015

Since you are searching by ID, you might want to make your life easier by assigning an ID to each circle when you append them and then leverage that during your search. Here is what I mean:

// Append a circle
nodeEnter.append("svg:circle")
    .attr("id",function(d) {return "id_" + d.id}) // assign ID to circle
.attr("r", 8)
    ....

Then in the search:

this.searchNode = function (id) {
    var searchedNode = findNode(id);
    if(searchedNode == null){
        //alert("Not Found");
        return false;
    }else {
        //alert("Found");
        d3.selectAll("#id_" + id) // select circle based on ID
            .transition().duration(350)
            .attr("r",20) // temporarily increase the radius, or do something else
            .transition().duration(350)
            .attr("r",8);

        upd(searchedNode);
    }   
}

Updated FIDDLE.

This is a simple and straightforward way...but there are really many ways to achieve what you want.

Upvotes: 0

Stephen Thomas
Stephen Thomas

Reputation: 14053

Without the full code it's hard to say for certain, but something like the following

d3.select(searchedNode).attr('r',newRadius).style('fill', newColor);

Upvotes: 0

Related Questions