0

Is it possible to animate a DOM Object by a css-property from a variable in jQuery ?

this code does not work, where...

html:

<a data-direction="prev" title="" href="#">prev</a>
<a data-direction="next" title="" href="#">next</a>

javascript:

var _direction = $(this).data('direction'),
    _padding = (_direction == 'prev') ? 'margin-left' : 'margin-right'; //set css

$(this).animate({_padding:$(this).width(), opacity: 0},{duration: 320, complete:

    function() {

        console.log("done!");       
        $(this).removeAttr('style');
    }
});

Does anybody know a work around ?

2 Answers 2

1

You could use the eval() function, but that's not a nice solution at all.

A better method would be to simply use the _direction variable as a flag, try this:

var _direction = $(this).data('direction')
var settings = { opacity: 0 };

if (_direction == 'prev') 
    $.extend(settings, { margin-left: $(this).width() });
else
    $.extend(settings, { margin-right: $(this).width() });

$(this).animate(settings, {duration: 320, complete:
    function() {
        console.log("done!");       
        $(this).removeAttr('style');
    }
});
Sign up to request clarification or add additional context in comments.

Comments

0

I think your issue is the _ before padding, this won't work because it's not a valid property. jQuery can't handle IE hacks like this. If you only want to animate when it's IE you have to use Something like:

if($.brower.msie && $.browser.version == 7.0){}

Also you are passing a second param as Object, use this instead:

.animate({}, 320, function(){});

If you wan't to set the property of _padding which is a variable you have to generate an object like:

var _direction = $(this).data('direction'),
_padding = (_direction == 'prev') ? 'margin-left' : 'margin-right'; //set css

var animationData = {opacity: 0};
animationData[_padding] = $(this).width();

// And within animate
.animate(animationData, 320, function(){})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.