Search code examples
javascriptmootools

Mootools morph using variable


I'm creating a javascript function for my website that accepts several parameters, and then uses said parameters to perform a morph. Rather normal stuff, however the morph doesn't work. It seems that by getting the css attribute I want to morph (ie height) as a variable, I am bugging.

Base code being used:

window.addEvent('load', function() {
    var box = $('box');
    var sfx = new Fx.Morph(box, {
        duration: 1000,
        transition: Fx.Transitions.linear
    });
    
    var cssParam = 'height';
    var endVal = '100';
    
    sfx.start({cssParam endVal});
    console.log(sfx);
});
#box {
    width:200px;
    height:200px;
    background-color: #FFFFFF;
    border: 1px solid #000000;
}
<div id="box"></div>

The morph is taking the variable cssParam literally, and is trying to morph cssParam to 100. Obviously I am doing this wrong, how do I fix this issue?


Solution

  • er

    this is not ES6/7 - you cannot use dynamic object members in JavaScript object literals just yet.

    this: sfx.start({cssParam endVal}); is wrong.

    rewrite to:

    var morphObject = {};
    morphObject[cssParam] = endVal;
    sfx.start(morphObject);
    

    in ES6, you will have:

    var obj = {
        ['foo' + Date.now()]: 42,
        [cssParam]: endVal
    };
    

    in a modern browser, the above will be fine (works in both FF and Chrome latest)