Search code examples
jqueryrandomrepeattabular

Add html elements randomly inside rows


I have a large grid, meant for a time line view. What I want is that the next divs are randomly added to the rows (not all rows), so that the grid is pretty filled with colored boxes. The divs are:

    <div class="bar ganttRed" id="b4" style="width: 330px;">
        <div class="label" style="color: rgb(191, 191, 191); float: left; margin-left: 23.7px;"> 2836DE
        </div>
    </div>

and

    <div class="bar ganttGreen" id="b6" style="width: 66px;">
        <div class="label" style="color: rgb(61, 61, 61); float: left; margin-left: 14px;"> 2142 FG
        </div>
    </div>

I just do not know how this should be done.

And check out my Jsfiddle for viewing the html grid.


Solution

  • Not sure this is what you want but you should get the idea...

    $('.div-table-row').each(function () {
    
        var color = getRandomColor();
        var bar = '<div class="bar" style="background-color: ' + color + '; width: ' + (Math.floor(Math.random() * 200) + 80) + 'px;"><div class="label">' + color + '</div></div>';
        $('.div-table-td:eq(' + Math.floor(Math.random() * 15) + ')', this).html(bar);
    });
    
    function getRandomColor() {
        var letters = '0123456789ABCDEF'.split('');
        var color = '#';
        for (var i = 0; i < 6; i++) {
            color += letters[Math.floor(Math.random() * 16)];
        }
        return color;
    }
    

    JSFiddle demo

    Edit:

    2 bars mode:

    JSFiddle demo