Selections example

A big part of prototyping JavaScript code is playing around in the browser, using the JavaScript console to manipulate values. Instead of hitting refresh and logging the output a whole bunch, you can do things in the browser and instantly see the result. To do this, you attach functions to the window global object.

In main.js, replace all its contents with the following:

import tableFactory from './chapter2/table-factory'; 
import * as d3 from 'd3';

window.d3 = d3;
window.tableFactory = tableFactory;

This attaches the tableFactory function and D3 library to the global window object, so we can now use both freely in the console.
In Chrome's developer console, type the following two lines:

d3.selectAll('.table').remove(); 
tableFactory([
[1,2,3,4,5,6],
['q', 'w', 'e', 'r', 't', 'y'],
['a', 's', 'd', 'f', 'g', 'h'],
['z', 'x', 'c', 'v', 'b', 'n']
]);
Psst! If you need to add a newline character in Chrome's Developer console, hold shift while pressing return. Note that you don't actually need to do this; you can type the above all as one line if it's easier. I've only presented it this way for clarity.

This removes the old table (if you didn't refresh it in the meantime) and adds a new table.

Now, let's make the text in all of the table cells red:

d3.selectAll('td').style('color', 'red')

The text will promptly turn red. Now, let's make everything in the table head bold by chaining two d3.selectAll() calls:

d3.selectAll('thead').selectAll('th').style('font-weight', 'bold')

Great! Let's take nested selections a bit further and make table body cells green in the second, fourth, and sixth columns:

d3.selectAll('tbody tr').selectAll('td')
.style('color', (d, i) => { return i%2 ? 'green' : 'red'; })

The two d3.selectAll() calls gave us all the instances of <td> in the body, separated by rows, giving us an array of three NodeList objects with six elements each: [ NodeList[6]NodeList[6], and NodeList[6] ]. These are in the _groups array returned by d3.selectAll(), whereas the <tr> selections are stored in the _parents array. We then used .style() to change the color of every selected element.

Using a function instead of a static property gave us the fine-grained control we needed. The function is called with a datum argument (we'll discuss more on that later) and an index of the column it's in; that is, the i variable. Then, we simply return either green or red, based on the current index.
One thing to keep in mind is that chaining selections can be more efficient than OR selectors when it comes to very large documents. This is because each subsequent selection only searches through the elements matched previously.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset