tags:

views:

26

answers:

2

Hi,

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

A: 

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;

        /*Using variable as CSS property - This doesn't work */
        $(this).animate(animationProperties, 1000);

        /*Using variable as the CSS Values - This does */
        $(this).animate(animationProperties, 1000);
    });
}
Ionuț G. Stan
thanks! ...this sorted my problem!
paddywhack
A: 

The "not working" part does not work because you just cannot use variable values to declare fields in JSON. To workaround this you should have (replacing the not working part) :

// Create an empty object
var newStyle = { };
// Add a dynamically named field
newStyle[cssProperty] = moveTo;
// Start the animation
$(this).animate(newStyle, 1000);
Shtong
Thanks Shtong that answered my question! I must add though that the first line was incorrect, that variable is undefined so I just changed it tovar newStyle = {};and it worked!Thanks again!
paddywhack
Hah ! true.Fixed it ;)
Shtong