ata ata - 9 months ago 31
Javascript Question

Assigning translateY value by a string

I'm using some JavaScript to keep my sidebar fixed when user scrolls the page and when he reached to nearly bottom of the page, then make the sidebar

position: static
. This is the code:

<script>

window.onscroll = function() {
var px = window.scrollY;
var x = document.getElementsByClassName("sidebar");
var body = document.body,
html = document.documentElement;
var poht = Math.max( body.scrollHeight, body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight );
var poht2 = poht - 1300;

if(px < poht2){

if(px > 1700)
{x[0].style.position="fixed";x[0].style.transform="translateY(-1700px)";}

if(px < 1680){
if(x[0].style.position=="fixed")
{x[0].style.position="static";x[0].style.transform="translateY(20px)";}
}
}
// Problem occurs here

pos2 = -1 * 2300 - poht2;
pos2 = pos2 + "px";

else {x[0].style.position="static";x[0].style.transform="translateY(pos2)";}

}
</script>


At the last line (I mean
else
) when I want to calculate a value and assign it to
translateY()
, it's not working. What is the right form for doing that?

Thanks.

Answer Source

You can use string concatenation or template literal

x[0].style.transform = "translateY(" + pos2 + ")"

x[0].style.transform = `translateY(${pos2})`