tags:

views:

270

answers:

2

Is it possible to tween an element in percent in MooTools?

var slide = new Fx.Tween($('slide_box'));
$('next_slide').addEvent('click',function(){
    slide.start('left', '-100%');
});

But this code tween an element by 100px, not in percent.

+1  A: 

Maybe I'm overlooking something obvious, but is -100% not simply "0px"?

If an element has an absolute left position of 600px within a relatively positioned DIV, then shifting that element -100% left will result in a position of 0,0 (assuming the elements top is 0).

You could therefor achieve this with a morph.

$('slide_box').morph({'left':'0px'});

If you wished to shift the element by a value other than 100% then you could use a simple calculation to find out the required shift amount.

var shiftPercentage = 70;
var elementPosition = $('slide_box').getPosition().x;
var resultingShiftAmount = (elementPosition/100)*shiftPercentage;
$('slide_box').morph({'left':resultingShiftAmount+'px'});

Of course, depending on if you want to shift it in the positive or negative, make the variable 'resultingShiftAmount' positive or negative.

Hope this helps.

One further edit, it seems the Tween class has an option called 'unit'. This I imagine will not work quite as you expect it though.

var slide = new Fx.Tween($('slide_box'),{unit:'%'});
slide.start('left','-100%');

The above snippet of code will transform the element 'slide_box' the position of -100% relative to its containing element (at least in my brief tests this seems to be the case). For example - the containing element is sitting at 0px,0px has its position set to relative. Within this element there is an absolutely positioned element at 500px,0px. As I can see it, if you were to use the above code on this absolutely positioned element, it would be position absolutely from the 0,0 of the containing element, minus 100% of the containing elements width.

This seems a bit confusing to me, but that's what the tests showed.

Good luck!

Seidr
+2  A: 

Have a look at the base Fx class, there is an option to set the unit. Your example can be rewritten to:

$('next_slide').addEvent('click', function(){
    new Fx.Tween('slide_box', {
        unit: '%'
    }).start('left', -100);
});

You can see it in action here.

Ronald