New Grid Layout --

by mledbetter

HTML

<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js"></script>
<button id='newWin'>New</button><button id='killWin'>Delete</button>
<div id='container'>
</div>

CSS

#container {
    border: solid 1px Green;
    width: 600px;
    height: 100%;
    min-height: 500px;
}
.window {
    border: solid 1px Black;
    height: 20px;
    width: 20px;
    float: left;
}
.window span {
    padding-left: 10px;
}

JavaScript

( function() {
    var $container = $('#container'), containerProperties = {}, createNewWindow = function() {
    };
    containerProperties = {
        children : [],
        cindex : 0,
        cols : 1,
        height : $container.innerHeight(),
        rows : 1,
        width : $container.innerWidth()
    };
    createNewWindow = function() {
        var nextIndex = containerProperties.cindex + 1, windowTemplate = '';
        windowTemplate = ['<div id="', (Math.floor(Math.random() * 100000001)), '" style="display: none;" class="window"><span>', nextIndex, '</div>'].join('');

        containerProperties.children.push($(windowTemplate));
        containerProperties.cindex = nextIndex;
    }

    $('#newWin').click(function() {
        var $lastFloat = {}, $newWin = {}, cp = containerProperties, i, j, lastChildNumber, randHex = Math.ceil(Math.random() * 16777215).toString(16), stopClearIndex, winHeight, winWidth;

        // Add a new window to our list of windows
        createNewWindow();
        lastChildNumber = cp.children.length - 1;
        // Get the new window as a jQuery object
        $newWin = cp.children[lastChildNumber];

        $newWin.css('backgroundColor', '#' + randHex);
        $container.append($newWin)
        winHeight = cp.height / cp.rows;
        winWidth = cp.width / cp.cols;

        for( i = 0, j = cp.children.length; i < j; i += 1) {
            cp.children[i].outerHeight(winHeight).outerWidth(winWidth);
        }

        if ((cp.children.length / cp.cols === Math.floor(cp.children.length / cp.cols)&& 
            (cp.children.length / cp.rows === Math.floor(cp.children.length / cp.rows)))) {
            if(cp.cols > cp.rows) {
                cp.rows++;
            } else {
                cp.cols++;
            }
        }
        $newWin.show();
    });

    $('#killWin').click(function() {
        var $win = containerProperties.children.splice(-1, 1)[0];
        $win.remove();
        cp.cindex -= 1;
    });
}());