0

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.

svtslvskl
  • 619
  • 1
  • 7
  • 9
  • Something to consider: it _may_ be useless to link a "big" library like jQuery only _if_ you host it yourself. You can use the jQuery CDN or Google's CDN to do the heavy lifting for you on the client side. jQuery gives you a tremendous development advantage over raw JavaScript. That's why it was created in the first place. Also, jQuery is **pure JavaScript**. – jrd1 Aug 11 '13 at 12:14
  • What is `x`? A number? A string? – Jonathan Naguin Aug 11 '13 at 12:16
  • 1
    So long as you've got an appropriate value for `x` 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 Aug 11 '13 at 12:20

3 Answers3

8

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

element.style.setProperty("--my-var", jsVar + 4);
user
  • 23,260
  • 9
  • 113
  • 101
6

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.

2

I think you are looking for something like this

var xx = 100
document.getElementById("block").style.width = xx+'px';
Pumpkinpro
  • 837
  • 4
  • 5