How can I animate a calculated position using jQuery

So, I have a variable with a calculated position that centers the element using jQuery, because I did it because I don’t know the width of the element, so I made it dynamic.

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

Then I tried to animate it in the center (value of $ result) as follows:

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

Unfortunately, this did not work, only the upper value moved.

Any advice is greatly appreciated, thanks.

+5
source share
2 answers

jsBin demo

If you are already using calc (CSS3), then you will have nothing against using it in 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 old browsers, you can simply use .animate() , as you did ,
moving the element up to 50%, but also in the field - half-widths with half width (to center it):

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

jsBin demo (solution for crossbrowsers)

+3
source

jQuery animate will not accept css3 calc as a valid pixel value. You must first calculate that 50% .

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

Then use this in $result .

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

This should give you the position of the horizontal pixel for its animation.

0
source

Source: https://habr.com/ru/post/1232752/


All Articles