Last Updated: March 02, 2016
·
1.122K
· eltonmesquita

Set width and height based on viewport dimentions - Vanilla Javascript

/******************************************************* *
**
** Function to set an element dimensions relative
** to the viewport dimensions.
**
** Pass the selector and the dimensions you want
** to set. If you need just the height, set width
** to 0 or false.
**
** No dependency.
**
* *******************************************************/

function setDimensions(el, width, height) {
  var el = document.querySelectorAll(el),
      w  = Math.max(document.documentElement.clientWidth, window.innerWidth || 0),
      h  = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);

  if(width) {
    for (var i = 0; i < el.length; ++i) {
      el[i].style.width = w * (width/100) + "px";
    }
  }

  if(height) {
    for (var i = 0; i < el.length; ++i) {
      el[i].style.height = h * (height/100) + "px";
    }
  }
}