JSFiddle - React, Tailwind, and code Playground

by Maria Karanasou

HTML

<script src="//d3js.org/d3.v4.min.js"></script>
<form>
  <fieldset>
    <legend>Selecting elements</legend>
    <p>
      <label>Select list</label>
      <select id="myList">
        <option value="1">one</option>
        <option value="2">two</option>
        <option value="3">three</option>
        <option value="4">four</option>
      </select>
    </p>
  </fieldset>
</form>
<div id="thediv">
  <svg>
    <rect id="one" width="100" height="100" x="10" y="10"></rect>
    <rect id="two" width="100" height="100" x="100" y="10"></rect>
    <rect id="three" width="100" height="100" x="200" y="10"></rect>
    <rect id="four" width="100" height="100" x="250" y="10"></rect>
  </svg>
</div>

JavaScript

(function() {

  var selectOne = function() {
    var value = d3.select("#myList").node().value;
    var text = null;
    switch (value) {
      case "1":
        text = "one";
        break;
      case "2":
        text = "two";
        break;
      case "3":
        text = "three";
        break;
      case "4":
        text = "four";
        break;
    }
    console.log(text)
    if (text) {
      d3.selectAll("rect").attr("opacity", 0); // hide all
      d3.select("#" + text).attr("opacity", 1); // show selected  
    }
  };

  var svg = d3.select("svg");
  var rect1 = d3.select("#one")
    .attr("fill", "green")
    .attr("opacity", 0.5) // can be conditional based on what the user chooses
    .on("click", function() {
      console.log("hey", d3.select(this).attr("id"))
    });

  var rect2 = d3.select("#two")
    .attr("fill", "blue")
    .attr("opacity", 0.5) // can be conditional based on what the user chooses
    .on("click", function() {
      console.log("hey", d3.select(this).attr("id"))
    });

  var rect3 = d3.select("#three")
    .attr("fill", "red")
    .attr("opacity", 0.5) // can be conditional based on what the user chooses
    .on("click", function() {
      console.log("hey", d3.select(this).attr("id"))
    });


  var rect4 = d3.select("#four")
    .attr("fill", "black")
    .attr("opacity", 1) // can be conditional based on what the user chooses
    .on("click", function() {
      console.log("hey", d3.select(this).attr("id"))
    });

  d3.select("#myList").on('change', selectOne)

})()