Skip to content

Instantly share code, notes, and snippets.

Last active May 25, 2020
What would you like to do?
Multiple HTML inputs linked with d3.js
license: mit

This is an example of implimenting multiple HTML inputs using <range> input tags and using them to adjust a d3.js drawn svg element (a rectangle).

It is used as an example and described in the book D3 Tips and Tricks.

<!DOCTYPE html>
<meta charset="utf-8">
<title>Double Input Test</title>
<label for="nHeight"
style="display: inline-block; width: 240px; text-align: right">
height = <span id="nHeight-value"></span>
<input type="range" min="1" max="280" id="nHeight">
<label for="nWidth"
style="display: inline-block; width: 240px; text-align: right">
width = <span id="nWidth-value"></span>
<input type="range" min="1" max="400" id="nWidth">
<script src=""></script>
var width = 600;
var height = 300;
var holder ="body")
.attr("width", width)
.attr("height", height);
// draw a rectangle
.attr("x", 300)
.attr("y", 150)
.style("fill", "none")
.style("stroke", "blue")
.attr("height", 150)
.attr("width", 200);
// read a change in the height input"#nHeight").on("input", function() {
// read a change in the width input"#nWidth").on("input", function() {
// update the values
// Update the height attributes
function updateHeight(nHeight) {
// adjust the text on the range slider"#nHeight-value").text(nHeight);"#nHeight").property("value", nHeight);
// update the rectangle height
.attr("y", 150-(nHeight/2))
.attr("height", nHeight);
// Update the width attributes
function updateWidth(nWidth) {
// adjust the text on the range slider"#nWidth-value").text(nWidth);"#nWidth").property("value", nWidth);
// update the rectangle width
.attr("x", 300-(nWidth/2))
.attr("width", nWidth);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment