JavaScript calculate with viewport width/height

Viewed 41995

I am trying to set a responsive point in my mobile Webview and did this:

var w = window.innerWidth-40;
var h = window.innerHeight-100;

This works great so far. But the values -40 and -100 are not in the viewport scaling height and width.

When I do this:

var w = window.innerWidth-40vw;
var h = window.innerHeight-100vh;

as it should be to stay responsive and relative to the viewport - the JS does not work anymore. I think vh and vw works only in CSS ? How can I achieve this in JS ?

Pleas no JQuery solutions - only JS!

Thanks

8 Answers

The simplest way to do this, if you can fully edit the page, is to make a css class that has -40vw and -100vh like so:

CSS:

.class{
    width: -40vw;
    height: -100vh;
}

JS:

element.classList.add("class");

Note: "classList" is not supported in Internet Explorer 9. If you want it to work in all browsers, use this for JS instead:

function myFunction() {
    var element, name, arr;
    element = document.getElementById("myDIV");
    name = "mystyle";
    arr = element.className.split(" ");
    if (arr.indexOf(name) == -1) {
        element.className += " " + name;
    }
}

you just need to surround it in quotes I think. var w = window.innerWidth = "40vw" var w = window.innerWidth = "40vw"

this is my solve with you can use CSS;

    // calc dynamic customer device height/width
    let vh = window.innerHeight * 0.01,
        vw = window.innerWidth * 0.01;
    document.documentElement.style.setProperty('--vh', `${vh}px`);
    document.documentElement.style.setProperty('--vw', `${vw}px`);

How to use in CSS ?

If you will use 100vh or 100vw with this method, you should set 100vh/100vw for uncompatible browser.

Examples;

.wrapper{
    height: 100vh; /* Fallback for browsers that do not support Custom Properties */
    height: calc(var(--vh, 1vh) * 100);
}

.slide-container{
    height: calc(var(--vh, 1vh) * 100 - var(--menuHeight) - var(--footerHeight));
}

.little-image{
    width: calc(var(--vw, 1vw) * 5);
    margin-bottom: calc(var(--vh, 1vh) * 1);
}

/* and more.. */

This isn't a universal solution, but it's a much simpler implementation if you're working with a page that is always 100% displayed within the viewport (ie, if the body doesn't have to be scrolled and always matches the window width and height).

let vh = document.body.getBoundingClientRect().height;

This sets the vh variable to the pixel value of the document body with just one line of code.

Useful for game dev and other scenarios where you have the body affixed to the viewport.

get vmin in px

function vmin(){
    return window.innerHeight < window.innerWidth ? window.innerHeight: window.innerWidth;
}
Related