-
Notifications
You must be signed in to change notification settings - Fork 34
/
interactivity.Rmd
290 lines (212 loc) · 8 KB
/
interactivity.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
# Interactivity <i class="fas fa-mouse-pointer"></i>
Read: *IDVW2*, Chapter 10 Interactivity
<script src="https://d3js.org/d3.v7.js"></script>
## Binding event listeners to SVG elements
```{asis}
<svg width="300" height="200">
<rect width="300" height="200" fill="lightblue"></rect>
<circle cx="50" cy="75" r="20" fill="blue"></circle>
<ellipse cx="175" cy="100" rx="45" ry="30" fill="green"></ellipse>
<text x="100" y="150">(100, 150)</text>
<line x1="250" y1="150" x2="275" y2="175" stroke="red" stroke-width="5"></line>
</svg>
```
It's helpful to think carefully about what you want to happen when an event listener is triggered and what information you need. Open Developer Tools and try these in the Console. Note that event management [changed in v6](https://observablehq.com/@d3/d3v6-migration-guide#events){target="_blank"} so code written for earlier versions of D3 will not work.
### Do something unrelated to the element that received the event
``` js
d3.select("svg")
.on("click", function () {
d3.select("svg")
.append("text")
.attr("x", "100")
.attr("y", "40")
.text("Hello World");
});
```
### Change an attribute of the element that received the event
``` js
d3.select("line")
.on("click", function() {
d3.select(this)
.attr("stroke-width", "10");
});
```
In the context of event handlers, "this" is the element that received the event, a.k.a. what you clicked on if it's a click event. An alternative ($\geq$ v6, see link above) is to pass the event and access the element with `event.currentTarget`:
or
``` js
d3.select("line")
.on("click", function(event) {
d3.select(event.currentTarget)
.attr("stroke", "yellow");
});
```
### Get the value of an attribute of the element that received the event
``` js
d3.select("circle")
.on("click", function(event) {
const rad = d3.select(event.currentTarget).attr("r");
d3.select("text")
.text(`The radius is ${rad} pixels.`);
});
```
### Do something with the data bound to the element that received the event
``` js
d3.select("circle")
.data([{s: "red", sw: "15"}])
.on("click", function(event, d) {
d3.select(event.currentTarget)
.attr("stroke", d.s)
.attr("stroke-width", d.sw);
});
```
**Note that starting with v6, the data is the 2nd parameter to be passed: `function(event, d)`. In addition, note that you do not need to pass `d` again when accessing the data: for example we use `d.s` not `d => d.s`**.
As in the previous example, `d3.select(this)` can be used instead of `d3.select(event.currentTarget)`.
Try changing the data value bound to the circle with `d3.select("circle").datum("10")` and clicking again.
### Get the svg location of the event
``` js
d3.select("svg")
.on("click", function(event) {
d3.select("text")
.text(`(${d3.pointer(event).map(Math.round)})`)
});
```
(Up to v5, `d3.mouse(this)` was used instead of `d3.pointer(event)`.)
## Separating the function and event listener
Examples
``` js
function goyellow() {
d3.select(this)
.attr("fill", "yellow")
};
```
``` js
d3.select("circle")
.on("mouseover", goyellow);
```
## HTML buttons
``` html
<button type="button" onclick="showdate()">Click for date</button>
```
``` js
function showdate() {
console.log(Date());
}
```
<button type="button" onclick="showdate()">Click for date</button>
### Exercise
Add buttons as indicated to [this file](https://raw.githubusercontent.com/jtr13/d3book/main/code/vertical_bar_button_exercise.html).
## Radio buttons
HTML:
``` html
<p id="color" style="background-color: silver; color: white;">
Please select your favorite primary color:</p>
<input type="radio" name="fav_color" value="red">red</input>
<input type="radio" name="fav_color" value="blue">blue</input>
<input type="radio" name="fav_color" value="yellow">yellow</input>
```
Note:
* `type` is always `radio` for radio buttons
* `name` is shared for a group of radio buttons
* `value` is unique
JavaScript:
``` js
d3.selectAll('input[name="fav_color"]')
.on("click", function(event) {
var favcolor = event.currentTarget.value;
d3.select("p#color").style("color", favcolor);
});
```
<p id="color" style="background-color: silver; color: white;">Please select your favorite primary color:</p>
<input type="radio" name="fav_color" value="red">red</input>
<input type="radio" name="fav_color" value="blue">blue</input>
<input type="radio" name="fav_color" value="yellow">yellow</input>
<script>
d3.selectAll('input[name="fav_color"]')
.on("click", function(event) {
const favcolor = event.currentTarget.value;
d3.select("p#color").style("color", favcolor);
});
</script>
## Dependent event listeners
In these examples, the behavior or existence of one event listener depends on another.
### Global variable example
Here the circle click behavior depends on the value of the radio button: if the "Move left" radio button is checked, the circle will move left *when clicked*. If the "Move right" radio button is checked, the circle will move right *when clicked*.
A global variable is used to keep track of the radio button value. The event listener on the circle conditions the behavior on the value of this global variable.
```{asis}
<div id="rad" style="margin-left: 30px">
<h4>Click the circle.</h4>
<input type="radio" name="direction" value="left" checked="true"> Move left
<input type="radio" name="direction" value="right"> Move right<br>
<svg id='radio' width='300' height='200'>
<rect x='0' y='0' width='300' height ='200' fill = 'lightblue'></rect>
<circle cx='150' cy='100' r='20' fill='red'></circle>
<text x='10' y='190' style = 'font-size: 80%;'>svg#radio</text>
</svg>
</div>
```
<div style="margin-left: 30px">
```{js}
// global variable keeps track of which radio button is clicked
let action = "left";
d3.select("div#rad")
.selectAll("input")
.on("click", function() { action = d3.select(this).node().value; });
// circle click behavior depends on value of "action"
d3.select("svg#radio").select("circle")
.on("click", function () {
let cx_new;
if (action == "left") {
cx_new = +d3.select(this).attr("cx") - 50;
if (cx_new < 20) cx_new = 20;
} else {
cx_new = +d3.select(this).attr("cx") + 50;
if (cx_new > 280) cx_new = 280;
}
d3.select(this)
.transition()
.duration(500)
.attr("cx", cx_new);
});
```
</div>
### Turn off event listener
In this example, the event listeners on the squares are turned on or off depending on the value of the radio button. Event listeners can be removed by setting the behavior to `null`.
```{asis, echo=knitr::is_html_output()}
<div id="rad2" style="margin-left: 30px">
<h4>Click a square.</h4>
<input type="radio" name="square" value="red" checked="true"> Red active
<input type="radio" name="square" value="blue"> Blue active<br>
<svg id='radio2' width='300' height='200'>
<rect x='0' y='0' width='300' height ='200' fill = 'lightblue'></rect>
<rect id='red' x='75' y='75' width='50' height='50' fill='red'></rect>
<rect id='blue' x='175' y='75' width='50' height='50' fill='blue'></rect>
<text x='10' y='190' style = 'font-size: 80%;'>svg#radio2</text>
</svg>
</div>
```
<div style="margin-left: 30px">
```{js}
// movement function
const jump = function () {
d3.select(this).transition().duration(500)
.attr('y', '0')
.transition().duration(500).ease(d3.easeBounce)
.attr('y', '75');
};
// initial setup: add event listener to red square
d3.select("svg#radio2")
.select("rect#red")
.on("click", jump);
// switch event listeners if radio button is clicked
d3.select("div#rad2").selectAll("input")
.on("click", function () {
if (d3.select(this).node().value == "blue") {
d3.select("svg#radio2").select("rect#blue").on("click", jump);
d3.select("svg#radio2").select("rect#red").on("click", null);
} else {
d3.select("svg#radio2").select("rect#red").on("click", jump);
d3.select("svg#radio2").select("rect#blue").on("click", null);
}
});
```
</div>