Khoo Wing Hang
Khoo Wing Hang

Reputation: 39

how to use css to style if-else statement in d3

I currently have the following d3 code.

<script>


  var dataset = [14, 5, 26, 23, 9];

  d3.select("body").selectAll("p")
.data(dataset)
.enter()
.append("p")
.text(function(d) {
  if (d > 10)
  {
    return "Warning: Joe watched " + d + " cat vidoes today.";
  }
  else {
    return "Joe watched " + d + " cat vidoes today.";
  }});

how can i make the {return "Warning..."} part red with an external css? Thank you very much for the help!

Upvotes: 0

Views: 234

Answers (1)

Xavier Guihot
Xavier Guihot

Reputation: 61774

If you want to use an external css, then you can associate your text element with a class:

.attr("class", function() { return d > 10 ? "red_text" : "green_text" });

You can also use the style setter to set the color directly from javascript:

.style("fill", function() { return d > 10 ? "red" : "green" });

Upvotes: 3

Related Questions