Last Updated: March 02, 2016
·
1.407K
· 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";
    }
  }
}

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside