jQuery Bootstrap Grid Generator

I wanted to be able to dynamically create bootstrap grids so I wrote this. Then I figured it was handy enough that it was worth sharing.

Grant it, you will likely need to tweak it for your own needs but you'll be like 90% there. Some people like or need documentation. Some people despise documentation. I have listed the code both ways. You are welcome.

Please freely use this. You don't have to give me credit for anything. However, it would make my day if you drop me a line and tell me that you did. You can find my contact info on the About Page.

The Code (Commented)

I commented the ever lovin' crap out of this.


// We expect an array of rows.
// A row is an array of 1 to 12 jQuery DOM objects.
function bootstrap_create_grid (rows) {

    // Make the bootstrap container div.
    var container_div    = $('<div />').addClass('container-div');
    // The CSS class names for bootstrap grid.
    var types_of_columns = [
        'col-xs', 'col-sm-', 'col-md-', 'col-lg-', 'col-xl-',
    ];

    // Loop over the rows.
    rows.forEach(function(row, index) {
        // Create a Bootstrap row div.
        var row_div = $('<div />').addClass('row');

        // Bootstrap grids have a maximum of 12 cells.
        var total_grid_cells     = 12;

        // Initialize remaining.  Since we have no cells yet this will be 12.
        var remaining_grid_cells = total_grid_cells;

        // Initialize this for later. It is how many grid cell slots
        // the current cell will take up.  This will always be
        // 1 through 12.
        var grid_cell_count      = 0;

        // Loop through each jQuery object in a row.
        row.forEach(function(item, index) {

            // Index is zero based so our position is index + 1.
            var position = index + 1;

            // If this is not the last cell.
            if(row.length != position) {
                grid_cell_count = Math.floor(
                    remaining_grid_cells / (row.length - index)
                );

            // Else, this is the last cell.
            } else {
                // Use up the remainder of the cell slots.
                grid_cell_count = remaining_grid_cells;
            }

            // Remove this cell's slot count from the remaining grid cells.
            remaining_grid_cells = remaining_grid_cells - grid_cell_count;

            // Initialize class string.
            var grid_classes  = ''
            // Frankly I have regrets about this.  I used it to allow us to put a space
            // before all classes except the first one.   An array and a join would have
            // been better.
            var class_counter = 0;

            // Loop through the types of columns (the CSS bootstrap grid prefixes).
            types_of_columns.forEach(function(class_prefix, index) {
                // Don't add a space if this is the first one.
                if (class_counter != 0) {
                    grid_classes += ' ';
                }

                // Add this cell's slot count to the end of the class string.
                grid_classes += class_prefix + grid_cell_count
                // Increment this so we start adding spaces.
                class_counter++;
            });

            // Create the cell's div and assign it the classes.
            $('<div />').addClass(grid_classes)
                // Then append the item to it.
                .append(item)
                // Then append ourselves to our row.
                .appendTo(row_div);
        });

        // Append the row to the container div.
        row_div.appendTo(container_div);
    });

    // Return the container div.
    return container_div;
};

The Code (Uncommented)

function bootstrap_create_grid (rows) {

    var container_div    = $('<div />').addClass('container-div');
    var types_of_columns = [
        'col-xs', 'col-sm-', 'col-md-', 'col-lg-', 'col-xl-',
    ];

    rows.forEach(function(row, index) {
        var row_div = $('<div />').addClass('row');

        var total_grid_cells     = 12;
        var remaining_grid_cells = total_grid_cells;
        var grid_cell_count      = 0;

        row.forEach(function(item, index) {

            var position = index + 1;

            if(row.length != position) {
                grid_cell_count = Math.floor(
                    remaining_grid_cells / (row.length - index)
                );
            } else {
                grid_cell_count = remaining_grid_cells;
            }
            remaining_grid_cells = remaining_grid_cells - grid_cell_count;

            var grid_classes  = ''
            var class_counter = 0;
            types_of_columns.forEach(function(class_prefix, index) {
                if (class_counter != 0) {
                    grid_classes += ' ';
                }
                grid_classes += class_prefix + grid_cell_count
                class_counter++;
            });

            $('<div />').addClass(grid_classes)
                .append(item)
                .appendTo(row_div);
        });

        row_div.appendTo(container_div);
    });

    return container_div;
};

Usage:

Here's an example of how you would make a grid using this code.

Warning: I did not test this code so treat it like pseudo code.

// A bunch of jQuery DOM objects.
imma_link   = $('<a />')
    .text('I am a link')
    .attr('href', '#code_snippets/js_jquery_bootstrap_grid_generator')
    .css('border', '1px solid #fff');
a_div       = $('<div />').text('I am a div.').css('border', '1px solid #fff');
another_div = $('<div />').text('I am another div.').css('border', '1px solid #fff');
div_1       = $('<div />').text('1').css('border', '1px solid #fff');
div_2       = $('<div />').text('2').css('border', '1px solid #fff');
div_3       = $('<div />').text('3').css('border', '1px solid #fff');
div_4       = $('<div />').text('4').css('border', '1px solid #fff');
div_5       = $('<div />').text('5').css('border', '1px solid #fff');

// Call it with an array of arrays (rows of objects).
my_grid = bootstrap_create_grid([
    [ imma_link, a_div, another_div ],
    [ div_1 ],
    [ div_2, div_3, div_4, div_5 ],
]);
// This should create a grid with:
// A link and Two divs on the first row.
// One div on the second row.
// Four divs on the third row.

// Throw the grid onto the body.
$('body').attach(my_grid);

Example Output:

Summary

Hope you like it. I found this to be quite handy so hopefully someone else out there can find a use for it as well.