Lucas Santos
Lucas Santos

Reputation: 1369

How can I animate a calculated position with JQuery

So I have a variable with a calculated position that centers the element with JQuery, reason I did this is because I will not know the width of the element so I made it dynamic like so.

var $x = $("#line").outerWidth();

var $result = "calc( 50% - " + $x +"px / 2 )";

Then I tried to animate it to the center (value of $result) like so:

   $("#line").animate({ 
        "left": $result,
        "top" : "15px"

    }, 1000 );

Sadly this did not work, only the top value moved.

Any advice is greatly appreciated, thank you.

Upvotes: 5

Views: 1236

Answers (2)

Roko C. Buljan
Roko C. Buljan

Reputation: 206121

jsBin demo

If you already use calc (CSS3) than you'll have nothing against using in your CSS:

Using CSS3 transition and calc()

#line{
    transition: 1s;
    /*...other stuff...*/
}

and in your jQuery (instead of .animate())

var outW2 = $("#line").outerWidth() / 2;

$("#line").css({ 
  left : "calc(50% - "+ outW2 +"px)",
  top  : 70
});

Using .animate() and negative margin (for centering)

For all older browsers, you can simply use .animate() as you did,
moving the element to 50% but also to a -half-width left margin (to center it):

var outW2 = $("#line").outerWidth() / 2;

$("#line").animate(){
  left: "50%",
  marginLeft : -outW2
}, 1000);

jsBin demo (crossbrowser solution)

Upvotes: 3

earl3s
earl3s

Reputation: 2373

jQuery's animate won't accept the css3 calc as a valid pixel value. You'll need to first calculate what 50% is.

var containerWidth = $("#line").parent().outerWidth();

Then use that in your $result.

var $result = containerWidth * 0.5 - $x * 0.5;

This should give you the horizontal pixel location to animate it to.

Upvotes: 1

Related Questions