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

When attempting to retrieve the data from a JSON file using an XMLHttpRequest, the result that is returned is [object object]

I am currently studying JSON and found a helpful guide on w3schools. Here is the code provided in the guide: https://www.w3schools.com/js/tryit.asp?filename=tryjson_ajax The guide also includes a sample JSON file: https://www.w3schools.com/js/json_demo.t ...

Transitioning to Material-ui Version 4

During the process of upgrading material-ui in my React Application from version 3.9.3 to version 4.3.2, I encountered an error message stating TypeError: styles_1.createGenerateClassName is not a function. I am feeling lost when it comes to transitioning ...

Applying CSS transition delays to multiple images

I'm having trouble implementing a transition delay in my CSS. I've tried adding it in various places but it doesn't seem to be working as expected. This is my CSS: .imageBox { position: relative; float: left; transition ...

How can one properly extend the Object class in JavaScript?

I have a scenario where I want to enhance a record (plain Javascript object) of arrays with additional properties/methods, ideally by instantiating a new class: class Dataframe extends Object { _nrow: number; _ncol: number; _identity: number[]; co ...

React fails to recognize the key prop

When creating a list of TSX elements, I utilized the following code: this.productsModel = this.state.products.map(o => ( <Grid.Column key> However, I encountered a warning from React: Warning: Each child in a list should have ...

Add Django template without adding an extra line break

In my main.html template, I have the following code: <p>{% include "pouac.html" %}{% include "pouac.html" %}</p> The file pouac.html contains just one line: <span>pouac</span> When rendered, the main.html template generates two ...

Is there a way to successfully include an apostrophe in a URL?

I am currently utilizing Node.js: var s = 'Who\'s that girl?'; var url = 'http://graph.facebook.com/?text=' + encodeURIComponent(s); request(url, POST, ...) This method is not functioning as expected! Facebook seems to be c ...

Having trouble retrieving data from the table with AJAX and CodeIgniter

I am currently developing a comprehensive HRM+CRM system (Human Resource Management and Customer Relation Management). I have encountered an issue while trying to generate an invoice for each customer. I am struggling to resolve this problem and would appr ...

Utilizing an Angular foreach loop for restructuring JSON data

I currently have an ng-repeat function that outputs arrays of objects in the following format: [ {"day":"10","title":"day","summary":"summary","description":"ok","_id":"53f25185bffedb83d8348b22"}, {"day":"3","title":"day","summary":"summary","description" ...

Retrieving a targeted JSON element and adding it to a fresh object

Hello everyone, I have an object that resembles the following structure: [ { "app": 1, "scalable": true, "zoomable": true, "cropBoxResizable": true }, { "app" ...

Material-inspired Design Device Compatible DIV slide with JS, JQuery, and CSS

My goal is to achieve something similar to this: Desired Live Website I am looking for a feature where clicking on the div will slide in content from the right, load an external page inside it, and close when prompted. The slider div should be device c ...

Fetch a document from a NodeJS Server utilizing Express

Is there a way to download a file from my server to my machine by accessing a page on a nodeJS server? I am currently using ExpressJS and I have attempted the following: app.get('/download', function(req, res){ var file = fs.readFileSync(__d ...

CSS smoothly scrolls upward within a set height restriction

Is there a way to use CSS to ensure that the scroll bar of a fixed-height message box is always at the bottom, displaying the latest entry? Currently, as more messages populate the chat box main section, everything inside remains static. The only way to v ...

Toggling the visibility of a div using JavaScript

When I click the button, I want to show and then hide a div. However, it doesn't work on the first click - only on the second click. How can I make it work on the first click? HTML <p>Click the button</p> <button onclick="myFu ...

Position 2 identical classes side by side on the horizontal axis

Currently enrolled in the MIMO HTML course and facing a challenge where I am unable to align both elements with the class="column" attribute horizontally using display: inline-block; I have attempted using float:right and other CSS properties to achieve a ...

Update the page when the React route changes

I am facing an issue with a function in a component that is supposed to load certain variables when the page is fully loaded. Interestingly, it works perfectly fine when manually reloading the page. However, if I use a NavLink to navigate to the page, the ...

Despite implementing an event listener, the Google Maps API is failing to resize properly when created using AJAX

Currently, I am facing an issue with the Google Maps API as the map generated is not resizing to fit the div. Instead, it shows a large grey area which is quite frustrating for me. Can someone please assist me in resolving this problem? Below is the code ...

In order to enhance your programming skills, avoid hard coding functions and ensure that data is returned after binding changes

I am trying to create a method where I can provide a DOM as a parameter and retrieve data from image_preview. The goal is to make image_preview reusable instead of hardcoding it inside the function. Additionally, I want to separate image_preview.model() an ...

What is the best way to save newly added elements on a webpage that were submitted by the

I am looking for a way to save the changes made by users on my webpage so that they can navigate to different pages and come back without losing any added elements. These changes should be retained even when the user goes back to edit the webpage, but I pr ...

The eccentricities of Angular Translate in Firefox and Safari

While everything functions correctly in Chrome, there seems to be an issue with changing the language in Safari and Firefox. angular.module('angularApp') .config(['$translateProvider', function ($translateProvider) { $translateProv ...