patocallaghan patocallaghan - 2 months ago 6
jQuery Question

Dynamically choosing css property in animation

It seems a straightforward thing but I'm not having much success. I'm just implementing a simple animation moving a div left or up using animate() but I would like to be able to set the "top" and "left" css properties dynamically. I would like to use the same function rather than have to have two, one for "left" and one for "top".

Here's some code which gives the idea.



function test($element){
$element.click(function(){
var cssProperty;
var direction = "left";
var moveTo = "100px";

if (direction === "top") {
cssProperty = "top";
} else {
cssProperty = "left";
}

/*Using variable as CSS property - This doesn't work */
$(this).animate({
cssProperty: moveTo
}, 1000);

/*Using variable as the CSS Values - This does */
$(this).animate({
left: moveTo
}, 1000);
});
}



Variables works on the css value side but not on the css selector side. Anyone have any suggestions?

Thanks

Answer

See this: http://www.jibbering.com/faq/faq_notes/square_brackets.html

function test($element){
    $element.click(function(){
        var cssProperty;
        var direction = "left";
        var moveTo = "100px";
        var animationProperties = {};

        if (direction === "top") {
            cssProperty = "top";
        } else {
            cssProperty = "left";
        }

        animationProperties[cssProperty] = moveTo;

        // This does work.
        $(this).animate(animationProperties, 1000);

        // Or else, using computed properties introduced in ES6.
        $(this).animate({
            [cssProperty]: moveTo
        }, 1000);
    });
}

Browser support for computed properties.