Using JavaScript to calculate dimensions based on the viewport's width and height

I have been trying to establish a responsive point in my mobile Webview by implementing the following JavaScript code:

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

So far, this solution has been working effectively. However, I noticed that the values -40 and -100 do not adjust according to the viewport scaling height and width.

When attempting to update the code as follows:

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

To ensure responsiveness and relative positioning within the viewport, using vw and vh units, the JavaScript stops functioning correctly. It seems that vw and vh units are only applicable in CSS. Is there a way to achieve this functionality purely in JavaScript?

Please refrain from suggesting JQuery solutions, as I am looking for a JavaScript-only approach!

Thank you

Answer №1

After researching on this website, I found a useful set of functions that can calculate values based on a percentage of the screen width or height:

function vh(percent) {
  var h = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
  return (percent * h) / 100;
}

function vw(percent) {
  var w = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
  return (percent * w) / 100;
}

function vmin(percent) {
  return Math.min(vh(percent), vw(percent));
}

function vmax(percent) {
  return Math.max(vh(percent), vw(percent));
}

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));

Incorporating the solution from this post enhanced my code!

Answer №2

Here is a suggestion for you:

function determineViewportSize() {

 var viewportWidth;
 var viewportHeight;

 // For modern browsers (Mozilla, Netscape, Opera, IE7)
 if (typeof window.innerWidth !== 'undefined') {
   viewportWidth = window.innerWidth,
   viewportHeight = window.innerHeight
 }

// For IE6 in standards compliant mode
 else if (typeof document.documentElement !== 'undefined'
 && typeof document.documentElement.clientWidth !== 'undefined' 
 && document.documentElement.clientWidth !== 0) {
    viewportWidth = document.documentElement.clientWidth,
    viewportHeight = document.documentElement.clientHeight
 }

 // For older versions of IE
 else {
   viewportWidth = document.getElementsByTagName('body')[0].clientWidth,
   viewportHeight = document.getElementsByTagName('body')[0].clientHeight
 }
 return [viewportWidth, viewportHeight];
}

For more information, visit:

Answer №3

One issue encountered is that JS lacks support for 40vh. To remedy this, the number of pixels equivalent to 40vh must be calculated initially before using it. Otherwise, an error will occur when attempting 1000 - 40vh.

The term 40vh signifies 40 % of viewport height. Therefore, window.innerHeight * 0.4 == 40vh

It should be noted that wh does not exist in JavaScript; only vh (which represents a percentage of the viewport height).

Answer №4

To achieve this task easily, when you have complete editing access to the page, you can create a CSS class with dimensions set to -40vw and -100vh like shown below:

CSS:

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

JS:

element.classList.add("custom");

Please note that "classList" is not compatible with Internet Explorer 9. To ensure cross-browser compatibility, use the following JavaScript code instead:

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

Answer №5

Maybe all you have to do is enclose it in quotation marks.

var width = window.innerWidth = "40vw"
var width = window.innerWidth = "40vw"

Answer №6

Here is a solution using CSS:

// calculate 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 can you incorporate this into your CSS?

If you plan to use 100vh or 100vw with this approach, make sure to set a fallback for incompatible browsers.

For instance;

.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.. */

Answer №7

If you're dealing with a webpage that constantly fits perfectly within the viewport, this method may be a simpler alternative to more universal solutions. This is especially handy when the body of the page never needs to be scrolled and always matches the width and height of the window.

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

With just one line of code, the vh variable is set to the pixel value of the document body, streamlining your implementation.

This technique is particularly useful in game development and similar scenarios where the body remains fixed within the viewport.

Answer №8

retrieve the value of vmin in pixels

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Invoking a nested function within an array

I need to trigger a function with a button click. The function I want to call is nested within another function, which is part of an array. demo = { volej: function(param) { (new initChartist).users(param); }, initPickColor: function(){ ...

Place the two buttons in position

I have a section where I need to include two buttons. One button on the left labeled "Sunday" and one on the right labeled "misc". I want the two buttons to be evenly placed within the area, so I assigned them the same class since they are the same size. ...

Django form submission triggers Jquery modal to confirm object deletion

I'm currently working with Django and Crispy forms while also utilizing the Shopify Embedded Apps SDK. My goal is to implement a modal window that prompts the user to confirm the deletion of an object. My progress code is attached below. Although I h ...

What is the method to establish a reference based on a value in programming?

Having some trouble setting the 'ref' of a TextInput from a value. Here's an example: var testtest = 'testvalue' <TextInput ref=testtest autoCapitalize="none" autoCorrect={false} autoFocus={false} placeholderTextColor="#b8b8b ...

Tips for repairing a horizontal line at the bottom of the <TD> tag and placing text on top

I am working with an HTML table that contains a single TR tag and two TD tags. Each TD has two HR tags creating horizontal lines, along with some text. I am looking for a way to keep the text aligned at the top of the TD and the horizontal line at the bott ...

The proper usage of middleware in vue-router

I've set up routes in Vue and added some middleware conditions before each route, but it's not functioning as expected. Below is the content of my router/index.js file: const token = computed(() => useAuthStore().token); // Main Router cons ...

By default, Nuxt 2.15.7 is automatically installed when you create a new Nuxt app

I am looking to develop a Nuxt app (version 3) using Vue. However, when I run the command npm create nuxt-app@version mousa, it automatically installs Nuxt2. How can I install Nuxt3 instead with this command? ...

Reorganizing objects upon insertion in Mongo DB

I am encountering an issue in my Node.js app where MongoDB is causing objects to be reordered when inserting new records into the database. I am using the following insert method: collection.insert(object, {safe:true}, function(err, result) { if (err) ...

Changing return values with Jest mocks in TypeScript

Here I am again with a very straightforward example. In summary, I require a different response from the mocked class. Below is my basic class that returns an object: class Producer { hello() { return { ...

What's the best way to target an input that's appearing as it slides in from the edge of the screen?

My webpage has an element called #cols that is three times wider than the <body>. This element contains three columns, each exactly as wide as the <body>. When a button is clicked, the #cols element slides over by the width of one column while ...

What is the process for retrieving data from a javascript file that was submitted through a form?

Can you help me with an issue I'm having with this code snippet? <form action="main.js"> <input type="text" required="required" pattern="[a-zA-Z]+" /> <input type="submit" value="Submit" /> </form> After c ...

Changing the background color of a page to match the background color of a button in React, which can be updated at any time

I have a special button called ArbitraryBtn that, when clicked, changes the page's background color to random colors: import React from 'react'; export const changeToArbitraryColor = () => (document.body.style.backgroundColor = ...

The comparison between exposing and creating objects in a Nodejs router file

Recently, I began using expressjs 4.0.0 and was impressed by the express.Router() object. However, a dilemma arose when I moved all my routes to another file - how do I expose an object to the routes file? In my server.js file: ... var passport = ...

What's the best way to align a bottom navigation bar in the center?

Hey there! I recently added a bottom navigation bar to my website using HTML and CSS code. However, I'm having trouble centering it at the bottom of the page. Any suggestions or solutions would be greatly appreciated. Attached are screenshots of the H ...

Guide on Implementing Link href in Next.js v12

When I set the href as a string, the link functions properly. However, when I use an object for the href, the link fails to work. Despite seeing the correct querystring when hovering over the link, it always takes me back to the first page. // ProdCard t ...

How to send parameters to the jquery .css() method

I'm attempting to create hyperlinks that can dynamically set inline styles for different elements on a webpage. I have managed to save the element and attribute settings in hidden span elements and retrieve them to display in an alert dialog. However, ...

I'm noticing multiple repeated entries appearing when I try to set the cookie - what could be causing

Currently, I am utilizing the library js-cookie instead of my previous use of jquery.cookie. I have encountered an issue related to duplicating cookie entries. There are occasions when I invoke the following method: Cookies.set('my-cookie-name', ...

"Border-radius becomes less prominent on pointer interaction in Chrome and Safari due to WebKit's behavior

Having an issue with a list inside a div. The problem arises when there is a div containing a list, which limits the visibility of items for users. If the limit is exceeded, a scroll bar appears inside the div to allow users to see more items. Additionally ...

The mat-table's data source is failing to refresh and display the latest

When I click on a column header to sort the table, a function should trigger and update the data. However, the data is not updating as expected. Below is the code for the function and the table: <table mat-table #table [dataSource]="dataSourceMD&qu ...

Unable to produce audio from files

Attempting to incorporate sound files into my project using https://github.com/joshwcomeau/redux-sounds but encountering difficulties in getting it to function. Below is the code snippet I utilized for setup. Unsure if webpack is loading the files correctl ...