JSFiddle - React, Tailwind, and code Playground

by prayerslayer

HTML

<script src="http://code.jquery.com/jquery-latest.js"></script>
<button id="copyButton">Copy everything</button>
<div class="vizroot" id="viz12">
    <button id="sortButton">Sort</button>
</div>

CSS

body {
  font: 10px sans-serif;
}

.bar rect {
  fill: steelblue;
}

.bar text {
  fill: white;
}

.axis path, .axis line {
  fill: none;
  stroke: black;
  shape-rendering: crispEdges;
}

svg {
    width: 100%;
    height: 100%;
}

.vizroot {
    border: 1px solid black;
}

.tinyviz {
    width: 100px;
    height: 100px;
}

JavaScript

var margin = {top: 0, right: 10, bottom: 20, left: 10},
    width = 960 - margin.left - margin.right,
    height = 500 - margin.top - margin.bottom;

var index = d3.range(24),
    data = index.map(d3.random.normal(100, 10));

var x = d3.scale.linear()
    .domain([0, d3.max(data)])
    .range([0, width]);

var y = d3.scale.ordinal()
    .domain(index)
    .rangeRoundBands([0, height], .1);

var svg = d3.select(".vizroot").append("svg")
  .append("g");

var bar = svg.selectAll(".bar")
    .data(data)
  .enter().append("g")
    .attr("class", "bar")
    .attr("transform", function(d, i) { return "translate(0," + y(i) + ")"; });

bar.append("rect")
    .attr("height", y.rangeBand())
    .attr("width", x);

bar.append("text")
    .attr("text-anchor", "end")
    .attr("x", function(d) { return x(d) - 6; })
    .attr("y", y.rangeBand() / 2)
    .attr("dy", ".35em")
    .text(function(d, i) { return i; });

svg.append("g")
    .attr("class", "x axis")
    .attr("transform", "translate(0," + height + ")")
    .call(d3.svg.axis()
    .scale(x)
    .orient("bottom"));

var sort = false;

var doSort = function( parent ) {

  if (sort = !sort) {
    index.sort(function(a, b) { return data[a] - data[b]; });
  } else {
    index = d3.range(24);
  }

  y.domain(index);

  d3.select( "#"+parent ).selectAll( "svg" ).selectAll( ".bar" ).transition()
      .duration(750)
      .delay(function(d, i) { return i * 50; })
      .attr("transform", function(d, i) { return "translate(0," + y(i) + ")"; });

};

$( "#sortButton" ).click( function() {
    doSort( $(this).parent().attr("id") );
});

$( "#copyButton" ).click( function() { 
    var secondViz = $(".vizroot" ).first().clone( true );
    secondViz.attr("id", "viz11" );
    secondViz.addClass( "tinyviz");
    $( "body" ).append( secondViz );
});