Exercice 4 bis : boxes

by CloughyLow

HTML

<div class="box modelBox" >
    <div class="innerBox">
        <label>
            How many divs do you want ?<br />
            <input type="range" id="inputNbr" value="5" max="10" min="1" step="1"><br />
            <input type="submit" value="ok"/>
        </label>
    </div>
</div>

<div class="box contentBox"> 
    
</div>

CSS

.box {
    width: 460px;
    height: 230px;
    background: #d2dd2d;
    border: none;
    text-align: center;
    color: #000;
    margin: 0 30px 30px 0;
    float: left;
}
.modelBox .innerBox {
    padding: 20px;
}
.modelBox input[type='text'] {
    width: 50%;
    text-align: center;
}
.contentBox {
    background: #ddd;
    position: relative;
}
.lego {
    float: right;
    font-size: 8px;
    width: 100%;
    height: 100%;
    background-color: #ddd;
}
.lego.eventrue {
    background-color: #d2dd2d;
}

JavaScript

function createDivs(from, to, number) {
    
    var rest_divs_to_create = number;
    var from = $(from);
    var to = $(to);
    var rest_width = from.width();
    var rest_height = from.height();

    
    $('.contentBox .lego').remove();
    to.append('<div class="lego lego0 eventrue" style=" width:' + rest_width + 'px; height: ' + rest_height + 'px;"></div>');
    rest_divs_to_create--;
    
    for ( i = 0; rest_divs_to_create >= 0 ; i ++) {
        var lastBoxClass = '.lego' + (i);
        var last_width = rest_width;
        var isEven = isEven == true ? false : true;
        if(isEven){
            rest_width = Math.floor(rest_width/2);
        } else {
            rest_height = Math.floor(rest_height/2);
        }
        $(lastBoxClass).append('<div class="lego even' + isEven +'" style=" width:' + rest_width + 'px; height: ' + rest_height + 'px;">' + (i+1) + '</div><div class="lego lego' + (i+1) + ' even' + isEven +'" style=" width:' + rest_width + 'px; height: ' + rest_height + 'px;"></div>');
        rest_divs_to_create--;
        console.log('lastBoxClass : ' + lastBoxClass);
    }
    
}

$('.modelBox input[type=submit]').click(function() {
    var nbr_wanted_divs = $('#inputNbr').val() != 0 ? $('#inputNbr').val() : 5 ;
    createDivs( '.modelBox', '.contentBox',  nbr_wanted_divs);
});