D3 Playground

Just testing out the capabilities of D3.js

by Josh Carroll

HTML

<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<button type="button" id="stopButton">Stop</button>
<div id="target"></div>

CSS

#target div {
    background-color: purple;
    color: white;
    text-align: right;
    margin-botton: 1px;
    margin-top: 1px;
}
#stopButton {
    position:absolute;
    top:0;
    left:0;
    z-index: 1000;
}

JavaScript

(function () {
    function toPixels(d) {
        return d + "px";
    }

    function getRandomInt(min, max) {
        return Math.floor(Math.random() * (max - min + 1)) + min;
    }

    function getMaxWidth() {
        return $(window).width() - 10;
    }

    function getMaxHeight(numItems) {
        return ($(window).height() - numItems) / numItems;
    }
    
    function throttle(func, timeout) {
        var id = 0;
        return function () {
            var that = this,
                args = arguments;

            clearTimeout(id);

            id = setTimeout(function () {
                func.apply(that, args);
            }, timeout);
        };
    }
    var data = [34, 54, 22, 84, 39, 9, 2, 14],
        maxWidth = getMaxWidth(),
        maxHeight = getMaxHeight(data.length),
        intervalPtr;

    $('#stopButton').on("click", function(){
        if(intervalPtr !== 0){
            clearInterval(intervalPtr);
            $(this).text("Start");
            intervalPtr = 0;
        } else{
            startRender();
            $(this).text("Stop");
        }
    });    
    
    $(window).on("resize", throttle(function () {
        maxWidth = getMaxWidth();
        maxHeight = getMaxHeight(data.length);
    }, 50));

    function startRender(){
        
    intervalPtr = setInterval(function () {
        data.shift();
        data.push(getRandomInt(50, maxWidth));
        render();
    }, 1100);
    }
    
    function render() {
        var labels = d3.select("#target").selectAll("div").data(data).text(String);

        labels.transition()
            .duration(1000)
            .style("width", toPixels)
        .style("height", function(){ return maxHeight + "px"; });

        labels.enter()
            .append("div")
            .text(String)
            .style("position", "relative")
            .style("width", 0)
            .transition()
            .duration(1000)
            .style("width", toPixels)
            .style("height",...