Reputation: 319
I am making a scatterplot using D3. I have the following function that allows the user to filter out certain points using a checkbox:
//un-optimized code, works fine
d3.selectAll("[name=v]").on("change", function() {
var selected = this.value;
display = this.checked ? "inline" : "none";
svg.selectAll(".dot")
.filter(function(d) {return selected == d.holidays;}) //returns 1 or 0
.attr("display", display);
});
This function uses the "display"
attribute to display the points. However I have a good number of points on the chart, and displaying the points again after un-checking and re-checking takes time on slower machines.
I am attempting to optimize it by changing the opacity to 0 when un-checked and vice versa. However I am relatively new to D3 and cannot figure out how to make this work.
Here is what I have currently. This code works partially - the checkbox is checked by default, and when the user un-checks it, the selected datapoints becomes transparent. However, any subsequent checks/unchecks do not do anything - the code simply instructs the browser to keep changing the opacity to 0.
d3.selectAll("[name=v]").on("change", function() {
var selected = this.value;
display = this.checked ? "inline" : "none";
svg.selectAll(".dot")
.filter(function(d) {return selected == d.holWkend;})
.style("opacity", 0);
});
So the above code makes the selected points invisible when the checkbox is unchecked. What am I missing in order to change the opacity of the selected points to 1 again when the checkbox is re-checked?
Here is the corresponding checkbox HTML code for reference (includes some custom CSS checkbox styling)
<input type="checkbox" id="switch-id" name="v" value="0" checked>
<label for="switch-id">Holiday</label>
<span class="fh-switch-knob"></span>
<input type="checkbox" id="switch-id" name="v" value="0" checked>
<label for="switch-id">Non-holiday</label>
<span class="fh-switch-knob"></span>
Thanks!
Upvotes: 2
Views: 4376
Reputation: 109232
All you need to do is use exactly the same code you have for display
to set opacity
:
d3.selectAll("[name=v]").on("change", function() {
var selected = this.value;
opacity = this.checked ? 1 : 0;
svg.selectAll(".dot")
.filter(function(d) {return selected == d.holWkend;})
.style("opacity", opacity);
});
Upvotes: 3