Felix Felix - 21 days ago 5
CSS Question

Animate function: change div width by using radio buttons

I try to create an interactive "game" like this:
http://www.nytimes.com/interactive/2010/11/13/weekinreview/deficits-graphic.html?_r=0

I have a rough draft and it is working nicely with checkboxes, now I want the same behaviour with radio buttons.

But if I click a radio button, then the div shrinks, if I click another one it shrinks again and again. The behavior should be: Click a radio button (shrink 10%) and then click the radion button (shrink 5%) it should grow a little bit. So it should always consider what one has clicked before.

Here is the JavaScript function so far:

function animateDiv(val) {
if (val=="voll") {
$('#cont').animate({width: '-=10%'}, 500);
}
else if (val=="halb") {
$('#cont').animate({width: '-=5%'}, 500);
}
else if (val=="null") {
$('#cont').animate({width: '-=0%'}, 500);
}
}


Markup:

<input id="radio" type="radio" name="kultur" onClick="animateDiv('voll')">Voll
<input id="radio" type="radio" name="kultur" onClick="animateDiv('halb')">Halb
<input id="radio" type="radio" name="kultur" checked="checked" onClick="animateDiv('null')">Null


The functionality of the checkboxes you can see here: http://labs.tageswoche.ch/budget

Answer

You need it to remember what the original width was. Maybe, before you animate, check if a .data('originalWidth') has been set. If it has not, set it to what the width is. Then, on each later animate, base it off of that. Something like...

function animateDiv(val) {
    var div = $('#cont');
    if(div.data('originalWidth') == undefined)
        div.data('originalWidth', div.width());

    var width = div.data('originalWidth');

    if (val=="voll")
        width *= .9;
    else if (val=="halb") 
        width *= .95;

    $('#cont').animate({width: width}, 500);
}