Pragyan Bezbaruah
Pragyan Bezbaruah

Reputation: 183

D3js include more than one style

Here is the code that I have written -

<!DOCTYPE html>
<meta charset="utf-8">
<html>
<style>
    div.bar{
        display: inline-block;
        width: 20px;
        height: 75px;
        background-color: blue;
        margin-right: 5px;
    }
</style>
<head>
    <title> Simplebar - Out Dataset </title>
    <script src="https://d3js.org/d3.v4.js"></script>
</head>
<body>
    <script type="text/javascript">
    d3.csv("officedata.csv", function(data){
            console.log(data);

    d3.select("body")
        .selectAll("div")
        .data(data)
        .enter()
        .append("div")
        .attr("class", "bar")
        .style("height", function(d){
            var bheight = d.age*5; //scales the bar height 10 times
            return bheight + "px";
            })
        .style("color", function(d){
            if( d.age > 30) { return "red"; }
            else { return "blue"; })
    });
    </script>
</body>
</html>

and here is the csv file -

name,age
pragyan,23
rashmi,26
tumon,40
debajit,50
dhiraj,19

I want to give condition that the color should be red if the age is above 30. I have tried the color part in a separate code and it was working but when I tried it in here, it is not working. Removing the color part, the height is working just fine.

How can I add two style properties? Please help.

Upvotes: 3

Views: 56

Answers (1)

Cyril Cherian
Cyril Cherian

Reputation: 32327

1) Instead of color use background-color.

2) Make the age a number by setting d.age = +d.age. Currently its a string so d.age > 30 will not work as expected.

        .style("background-color", function(d) {
          d.age = +d.age;
            if (d.age > 30) {
              return "red";
            } else {
              return "blue";
            }
        });

working code here

Upvotes: 1

Related Questions