Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 356
Lucas Santos Avatar asked Sep 27 '22 14:09

Lucas Santos


2 Answers

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)

like image 124
Roko C. Buljan Avatar answered Oct 04 '22 17:10

Roko C. Buljan


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.

like image 39
earl3s Avatar answered Oct 04 '22 19:10

earl3s