rekoDolph
rekoDolph

Reputation: 823

How do i select all nodes and apply a css style to all of them, D3

I have an array of nodes. I wish to click a HTML button and change the style of all those nodes to that one style.

(For example: when i search for a node or click to select, i want to click the 'clear' button so everything resets)

Surely there's an easy answer to this but i cant seem to get it

.node.selectedNode {
    width:50px;
    height:50px;
    stroke-width: 3px;
    stroke: #f00;
}

.node.unselectedNode {  
}

above is the CSS that i wish to alternate between

Upvotes: 2

Views: 926

Answers (3)

Santiago Rebella
Santiago Rebella

Reputation: 2449

lets say your node is rect, you can use the .on('click') to

button on click ==> set_variable a scope higher ==> call D3 function to rerender

var set_variable;
$('#button').on('click', function () {
  if(something) {set_variable="classA";}
  else {set_variable="classB";}

  D3Function();
});

D3Function ==> ...

canvas.selectAll("rect").data(scope.input).enter()
  .append("rect").call(yAxis)

  .attr("class", function(d, i) { return set_variable; })

  .on("click", function(d, i){ 
  //d is the document, i the index
   });

....

$('#reset').on('click', function () {
  set_variable="";     
  D3Function();
});

Upvotes: 1

jleft
jleft

Reputation: 3457

To add or remove a CSS class, you can use the selection.classed function:

// Select all elements with the node class
d3.selectAll(".node")  
    .classed("selectedNode", true) // Add the selectedNode class to the selection
    .classed("unselectedNode", false); // Remove the unselectedNode class to the selection

The selection.on function can be used to listen for a click on a button, for example, for the clear button functionality, if you have button like this:

<button id="reset">Clear</button>

Then you can set the classed appropriately:

var unselectAllNodes = function () {
    d3.selectAll(".node")
        .classed("selectedNode", false)
        .classed("unselectedNode", true);
};

// Call the unselectAllNodes function when this button is clicked
d3.select("button#reset")
    .on('click', unselectAllNodes);

Upvotes: 2

Austin Hartzheim
Austin Hartzheim

Reputation: 220

You can add classes to nodes with code like this: .attr("class", "link").

For more context, you can see the example. This particular example uses svg.selectAll() to select all elements with the link class, which may or may not work in your case. If you need more complex selections, the relevant documentation is here

As an alternative, the .attr method supports using a function to take action based on the data for a selected node. You can find more information in the documentation

Upvotes: 0

Related Questions