https://benclinkinbeard.com/d3tips/attrclass-vs-classed/





.attr('class') vs .classed()

There are three ways to style elements in D3.

The first option is using selection.style to set individual style properties. This is useful for demos and explorations, but when it comes to production-ready code you probably want to rely on CSS classes. This makes your styles more maintainable by keeping them in one place, and if you're working with a designer it's much easier for them to make changes without digging through your code.

Letting CSS do its job

The second way to style elements is by using selection.attr to set the classattribute.

If you've used D3 before you've almost certainly seen selection.attr. You can use it to set any attribute on any selection, including the class attribute. selection.attr('class', 'foo') will apply the CSS class foo to selection and selection.attr('class', 'foo bar') will apply both classes.

This is usually the way I apply classes in D3. Especially in scenarios where the same class is being applied to an entire selection, selection.attr('class', 'foo') just feels like the most straightforward approach.

Conditional styles

The third way to style elements is with the selection.classed method. This approach is well suited for applying a CSS class to some subset of a selection or turning a CSS class on or off after the initial construction. This change could be in response to new data, user interaction, etc.

For example, you could apply a CSS class to items with a negative value to bring them to a user's attention. selection.classed('boldAndRed', (d) => return d.value < 0) will apply the boldAndRed CSS class to any elements whose data item has a value property less than zero.

Or maybe you want to apply a class to all the nav items that are not the active item. Something like the following could do that.

d3.selectAll('nav a')
  .classed(
    'muted',
    (d, i, nodes) => {
      const node = d3.select(nodes[i])
      node.attr('href') !== document.location
    }
  )

Right tool, blah blah blah

To be clear, some of this comes down to personal preference. There's nothing stopping you from using selection.classed('foo', true) instead of selection.attr('class', 'foo') and they are functionally identical. I've simply adopted an approach where the method I use serves as an additional indicator of what is going on. When I see selection.classed in my code it's a hint that there is some kind of logic involved in applying that CSS class. When I see selection.attr used to set the class attribute I know it's a run of the mill, static assignment that will not change.







'코딩' 카테고리의 다른 글

javascript : 탬플릿 문자열 (백틱기호)  (1) 2018.12.24
d3 : 기본형  (0) 2018.12.23
javascript : 콜백함수  (0) 2018.12.22
javascript : 사용자 정의 객체  (0) 2018.12.22
.append ("g")란?  (0) 2018.12.22

+ Recent posts