Question

I am calculating the x variable earlier in the code and i want to insert that variable value in the inline style of the div, but it doesn't work, though it works perfectly if i insert constant like "100px".

var x;  
document.getElementById("block").style.position = "fixed";  
document.getElementById("block").style.left = x;  

Note: i want to get it working without using jquery because i am using only a couple of scripts on the website and it is useless to link a big library in my case.

Was it helpful?

Solution 2

Ok so I can't post comments yet but I've run into a similar problem before.

Without any additional code I can make an assumption that x is the calculated value and it is a number. It is invalid css to insert just a number into left thus you must append a unit to it before assign it to the property:

document.getElementById("block").style.left = x + 'px';

If that fixes your problem, then great! Otherwise please post how you calculate x between var x; to the assignment of x.

OTHER TIPS

If you came here looking how to set CSS variables in the inline style, here you go:

element.style.setProperty("--my-var", jsVar + 4);

I think you are looking for something like this

var xx = 100
document.getElementById("block").style.width = xx+'px';
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top