Learn
Introduction to D3
Styling your data

Now that you know how to access the datum associated with each element, it’s possible to start customizing the appearance of each element with two powerful methods: .attr() and .style().

  • The .attr() method takes two parameters, the HTML attribute you wish to change and the value you wish to assign it.
  • Similarly, the .style() method takes two parameters, the CSS property you wish to change and the value you wish to assign it.

As we saw in the previous exercise, both of these methods can take their second argument as a function that returns the desired value for the property or attribute.

Let’s take a look to build on the example we’ve seen throughout the lesson:

let dataset = [55,34,23,22,59]; let svg = d3.select("body") .selectAll("div") .data(dataset) .attr("id", function(d,i){ return "element-" + i; }) .style("width", function(d){ return d + "px"; });

Focusing on the last four lines of the example above, observe that both .attr() and .style() levereged an anonymous function with the d parameter to set the values based on the element data.

  • The .attr() method changed the HTML attribute id to be based on the element index in the dataset
  • The .style() method computed the width to be a function of the datum value

You can style your elements according to the value of their data and change the styling based on different conditions.

Instructions

1.

Use the .attr() method to assign a class of "bar" to all of the div elements in the d3 chain. All of the elements in this selection will now be styled with the same class. Click “Run” and observe what styles applied.

2.

It’s great to apply a class for shared common styles, but what about the styles that depend on the value of the data of each element? Customize the width of each div by using the .style() method. Use an anonymous function to compute the width in pixels to be:

d.amount * 50 + "px"

Click “Run” and observe the width of each div element reflect the number of views per YouTube video. That’s what we call data-driven styling!

Folder Icon

Sign up to start coding

Already have an account?