Three Clickable Rects

Three Clickable Rectangles

by Tim Williams

HTML

<div id="rectInfo" style="opacity:0">
<!-- Rect info will appear here -->
</div>

CSS

#rectInfo {
    background-color: white;
    position: relative;
    padding: 10px;
    width: 230px;
    height:100px;
    border: 2px;
    outline: grey solid thin;
  }
.formLabel{
  font-family: courier;
}

JavaScript

var rectData = [
  { "label":"one",   "x": 100, "y": 50,  "height": 100, "width":120, "color" : "green" },
  { "label":"two",   "x": 250, "y": 50,  "height": 100, "width": 120, "color" : "purple"},
  { "label":"three", "x": 400, "y": 50,  "height": 100, "width": 120, "color" : "red"}
];

var svg = d3.select("body").append("svg")
  .attr("width", 600)
  .attr("height", 200);

var rects = svg.selectAll("rect")
  .data(rectData)
  .enter();

rects.append("rect")
  .attr("x",     function (d)  { return d.x; })
  .attr("y",     function (d)  { return d.y; })
  .attr("height", function (d) { return d.height; })
  .attr("width",  function (d) { return d.width; })
  .style("fill",  function(d)  { return d.color; })
  .on('mouseover', function(d){
    var rectSelection = d3.select(this)
    .style({opacity:'0.5'})})
  .on('mouseout', function(d){
    var rectSelection = d3.select(this)
    .style({opacity:'1'})})
  .on("click", function(d){
    console.log("You clicked rectangle: " + d.label)
    console.log ("X position: " + d.x)
    console.log ("Y position: " + d.y)
// Old code that toggles opacity
/*    var active = rectInfo.active ? false : true,
       newOpacity = active ? 0 : 1;
*/
    d3.select("#rectInfo").style("opacity", 1);

    rectInfo.active = 1;

    // Form displayed in /div becomes visible onclick of a rect.
    // submit button clears the form. No data update yet.
    var infoForm = d3.select("#rectInfo").append("form")
    .attr("id", "foo")
    .attr("action", "javascript:submitForm();")
    .attr("method", "post")
    .attr("class", "formEle");


    infoForm.append("text")
    .attr("class", "formLabel")
    .text("Label: ");
    infoForm.append("input")
    .attr("name", "Label")
    .attr("size", "15")
    .attr("type", "text")
    .attr("value", d.label)
    .attr("class", "formEle");
    infoForm.append("br")
    .attr("class", "formEle");

    infoForm.append("text")
    .attr("class", "formLabel")
    .text("X pos: ");
   ...