I have the following code:
<div id="container"></div>
and in my JavaScript code, I am trying to set its left property value to the result of a calculation. This same calculation works in CSS but not when used in JavaScript code.
var element = document.getElementById("container");
element.style.left = "calc(" + (container.clientWidth + containerUnit + " / 2 - " + child.clientWidth + unit + " / 2") + ");";
But, console.log(element.style.left) returns: (blank value here). And upon setting this style in JS, no effect is made on the element.
containerUnint contains "px" and unit contains "%"
The problem is that you're passing an invalid value to calc(), so the browser is not applying it. You have to specify measurements for CSS to understand how to actually execute the calculation.
Your current concatenation compiles to something like:
calc(200 / 2 - 10 / 2);
I guess you're working in pixels, so you need to update your definition as follows:
element.style.left = "calc(" + (container.clientWidth + containerUnit + "px / 2 - " + child.clientWidth + unit + "px / 2") + ")";
Notice that you should also lose the trailing ;:
const element = document.getElementById("container");
const containerUnit = '%';
const unit = 'px';
element.style.left = "calc(" + (10 + containerUnit + " / 2 - " + 10 + unit + " / 2") + ")";
console.log(element.style.left)
<div id="container"></div>