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
Use window. innerWidth and window. innerHeight to get the current screen size of a page.
You can use the window. innerHeight property to get the viewport height, and the window. innerWidth to get its width. let viewportHeight = window.
A simple way to solve this is to use the viewport percentage unit vh instead of %. One vh is defined as being equal to 1% of a viewport's height. As such, if you want to specify that something is 100% of the latter, use " height: 100vh ". Or if you want to make it half the height of the viewport, say " height: 50vh ".
Based on this site you can write following function in javascript
to calculate your desired values:
function vh(v) {
var h = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
return (v * h) / 100;
}
function vw(v) {
var w = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
return (v * w) / 100;
}
function vmin(v) {
return Math.min(vh(v), vw(v));
}
function vmax(v) {
return Math.max(vh(v), vw(v));
}
console.info(vh(20), Math.max(document.documentElement.clientHeight, window.innerHeight || 0));
console.info(vw(30), Math.max(document.documentElement.clientWidth, window.innerWidth || 0));
console.info(vmin(20));
console.info(vmax(20));
I used this incredible question in my codes!
Try this:
function getViewport() {
var viewPortWidth;
var viewPortHeight;
// the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight
if (typeof window.innerWidth != 'undefined') {
viewPortWidth = window.innerWidth,
viewPortHeight = window.innerHeight
}
// IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)
else if (typeof document.documentElement != 'undefined'
&& typeof document.documentElement.clientWidth !=
'undefined' && document.documentElement.clientWidth != 0) {
viewPortWidth = document.documentElement.clientWidth,
viewPortHeight = document.documentElement.clientHeight
}
// older versions of IE
else {
viewPortWidth = document.getElementsByTagName('body')[0].clientWidth,
viewPortHeight = document.getElementsByTagName('body')[0].clientHeight
}
return [viewPortWidth, viewPortHeight];
}
Reference: http://andylangton.co.uk/articles/javascript/get-viewport-size-javascript/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With