Skip to content

1.Selection

yuanlii edited this page Jun 29, 2019 · 21 revisions

Selection

  • D3.select --> selects the first matching element
  • d3.selectAll --> selects all matching elements.

Update selection with functions

an example:

d3.selectAll('circle')
.attr('cx', function(d, i) {
	return i * 100;
});
  • d is the joined data
  • i is the index of the element within the selection

Another example (entire code):

<html>
    <head>
        <link rel="stylesheet" href="index.css">
        <title>Learn D3.js</title>
    </head>

    <style>
        rect {
	        fill: #ddd;
        }        
    </style>

    <body>
        <!-- begin by creating several squares  -->
        <svg width='800' height='600'>
            <g transform="translate(70, 20)">
                <rect width="30" height="30" y="0" />
                <rect width="30" height="30" y="40" />
                <rect width="30" height="30" y="80" />
                <rect width="30" height="30" y="120" />
            </g>
        </svg>

        <!-- define an action button -->
        <div class="menu">
            <button onClick="update();">Click to update rect elements using function(d, i)</button>
        </div>
        
        <script src="https://d3js.org/d3.v4.min.js"></script>
        <!-- reference to index.js -->
        <script src="index.js"></script>
    </body>
</html>

selection_square

Oftentimes will use anonymous function, but can also use named function as below:

function positionRects(d, i) {
	return i * 40;
  }

function update() {
	d3.selectAll('rect')
		.attr('x', positionRects
		);
}

Event Handler

We can add event handlers to selected elements using .on which expects a callback function into which is passed two arguments d and i. | "Event Call-back Function"

  • d is the joined data
  • i is the index of the element within the selection.
d3.selectAll('circle')
  .on('click', function(d, i) {
	// in the event call-back function, "this" variable is bound to DOM element
    d3.select(this)
      .style('fill', 'orange');
  });

Note that this is a DOM element and not a D3 selection so if we wish to modify it using D3 we must first select it using d3.select(this).

Clone this wiki locally