Animated Scale

by rjurd

HTML

<script src="http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js"></script>
<form id='myform' onsubmit='return false;'>
    <input type='text' id='left_input' value='0' class='required digits' />
    <div id='result'>&nbsp;</div>
    <input type='text' id='right_input' value='0' class='required digits'/>
    <input type='submit' onclick='calculate();' value='Go' />
</form>
<div id='box-animation'>
    <div id='left_box'>&nbsp;</div>
    <div id='right_box' style='float: right'>&nbsp;</div>
</div>

CSS

div, input {
    float: left;
}
#result {
    width: 100px;
    text-align: center;
}
#box-animation {
    border: 1px dashed black;
    width: 400px;
    height: 200px;
    position: relative;
    float: clear;
}
#box-animation div {
    width: 50px;
    height: 50px;
    border: 1px solid black;
    position: relative;
    top: 75px;
}

JavaScript

calculate = function() {
    if ($('#right_input').val() > 10) {
        $('#right_input').val(10);
    }
    if ($('#left_input').val() > 10) {
        $('#left_input').val(10);
    }

    var iLeft = $('#left_input').val();
    var iRight = $('#right_input').val();
    var totWeight = iLeft + iRight;
    var iLeftPer = iLeft / totWeight;
    var iRightPer = iRight / totWeight;
    var diff = ((iLeft - iRight) > 0) ? 1 : -1;

    $('#result').html(totWeight);

    var iLeftTop = diff * iLeftPer * (200 - 50);
    var iRightTop = iRightPer * (200 - 50);

    $('#left_box').html(iLeftTop + ': ' + iLeftPer);
    $('#right_box').html(iRightTop + ': ' + iRightPer);

    myanimation(iLeftTop, iRightTop);
};

$("#myform").validate({
    focusInvalid: false
});

$('input[type="text"]').each(function(index, element) {
    $(element).change(function() {
        calculate();
    });
    $(element).rules('add', {
        range: [0, 10]
    });
});

myanimation = function(ileft, iright) {
    var delay = 1000;
    $('#left_box').animate({
        top: ileft
    }, delay);
    $('#right_box').animate({
        top: iright
    }, delay);
};