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.
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.
Share Improve this question edited Oct 19, 2013 at 18:13 svtslvskl asked Aug 11, 2013 at 12:08 svtslvsklsvtslvskl 6191 gold badge7 silver badges9 bronze badges 3 |3 Answers
Reset to default 10If you came here looking how to set CSS variables in the inline style, here you go:
element.style.setProperty("--my-var", jsVar + 4);
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.
I think you are looking for something like this
var xx = 100
document.getElementById("block").style.width = xx+'px';
x
? A number? A string? – Jonathan Naguin Commented Aug 11, 2013 at 12:16x
what you've written should work (albeit I'd retrieve the element once, and use a cached variable to access it again). So, what happens, or doesn't happen, that goes against your expectations? – David Thomas Commented Aug 11, 2013 at 12:20