Search code examples
javascriptcss-variables

setting a css variable via javascript


I am trying to get the height and width of the browser window and display it on the body as well as changing the height to match.

Here's my current code:

window.onresize = window.onload = function() {
  width = this.innerWidth;
  height = this.innerHeight;
  document.body.innerHTML = width + 'x' + height; // For demo purposes
}

The above code displays the width and height on the body ok, now time to add it to a css variable:

var header = document.querySelector('.header')

window.onresize = window.onload = function() {
  width = this.innerWidth;
  height = this.innerHeight;
  header.style.setProperty('--height', height);
  header.style.setProperty('--width', width);
  document.body.innerHTML = width + 'x' + height; // For demo purposes
}

I know the code is not correct but I can't find any sample to compare with, here's a fiddle just in case the code is not enough.

https://jsfiddle.net/rbtwsxd8/6/


Solution

  • You have a number of different issues here:

    • (at least in the fiddle) you were trying to document.queryselect the header element before it existed
    • your debug code overwrote the header element by setting document.body
    • You omitted the units when setting the height and width (This used to work in "quirks mode" but will not work in modern doctypes.)
    • You added extra double hyphens when trying to set the height and width

    Here's a working version which corrects these problems:

    window.onresize = window.onload = function() {
      var header = document.querySelector('.header');
    
      // your original code used 'this.innerWidth' etc, which does work
      // (because the function is being run on the window object) but can
      // be confusing; may be better to refer to the window object 
      // explicitly:
      var width = window.innerWidth;
      var height = window.innerHeight;
    
      header.style.width = width + "px"; // need 'px' units
      header.style.height = height + "px";
      // the above is equivalent shorthand for
      // header.style.setProperty('height', window.innerHeight + 'px');
      // header.style.setProperty('width', window.innerWidth + 'px');
    
      // setting this inside the header, so we don't remove it in the process:
      header.innerHTML = width + "x" + height;
    }
    

    https://jsfiddle.net/pm7rgx4q/1/