0

I have a dataset, based on the values i want to print "Warning: joe has watched 14 cat videos today" in either black or red. if value is bigger than 10 its in red. How do i do this in using d3 or html formatting??

var dataset = [14, 5, 26, 23, 9];
d3.select("body").selectAll("p")
    .data(dataset)
    .enter()
    .append("p")
    .style('fill', 'darkOrange')
    .text(function(d, i){
        for (i=0; i<5; i++)
        {
            result = "Warning: Joe watched " + d + " cat videos today";
        }
        return result;
    });

Need it to look like this

enter image description here

Hitesh
  • 3,449
  • 8
  • 39
  • 57

1 Answers1

2

Check this out

Add style attribute to change color of text according to value of array

.style("color", function(d, i) {
      return d > 10 ? "#ff0000" : "#000";
    })

And add if else in .text(function(d, i){} to change text according to condition see in my answer

var dataset = [14, 5, 26, 23, 9];
d3.select("body").selectAll("p")
    .data(dataset)
    .enter()
    .append("p")
    .style('fill', 'darkOrange')
    .style("color", function(d, i) {
      return d > 10 ? "#ff0000" : "#000";
    })
    .text(function(d, i){
        for (i=0; i<dataset.length; i++)
        {
            if(d > 10)
            {
              result = "Warning: Joe watched " + d + " cat videos today";
             }
             else
             {
              result = "Joe watched " + d + " cat videos today";
             }
        }
        return result;
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://d3js.org/d3.v5.min.js"></script>
Nirali
  • 1,776
  • 2
  • 12
  • 23
  • Thanks it works, what does the part from the ? after mean?? And how come it does just change the values colour only?? – SavageBooBoo Apr 24 '18 at 04:11
  • @SavageBooBoo check my updated answer. I hope you get your answer – Nirali Apr 24 '18 at 04:14
  • 1
    @SavageBooBoo, the ? is a ternary operator, it is a shorthand for an if else statement, see this [question/answers](https://stackoverflow.com/q/6259982/7106086). – Andrew Reid Apr 24 '18 at 05:21