Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript get viewport height without overflow Y [duplicate]

I would like to get the viewport height of a screen, without the overflowY.

In other words, I want to see the height of the user's screen, NOT the entire website's page height including the overflowy which the user can then scroll down.

So, if he has an iphone and the iphone has 600px in height, then i want to get 600, and not the entire body including the scroll which can be higher.

This works fine but it is hacky, is there another solution? I failed to come up with anything else.

// First you forcibly request the scroll bars to be shown regardless if they will be needed or not.
$('body').css('overflow', 'scroll');

// Take your measures.
// (These measures WILL take into account scroll bars dimensions)
var heightWithScrollBars = $(window).height();
var widthWithScrollBars = $(window).width();

// Set the overflow css property back to it's original value (default is auto)
$('body').css('overflow', 'auto');
like image 554
Aflred Avatar asked Feb 12 '26 20:02

Aflred


2 Answers

Not entirely sure I understand, but if you want the users viewport / screen size you can access them through vanilla javascript like so

var viewportWidth = window.innerWidth + "px";
var viewportHeight = window.innerHeight + "px";

It will just get you a number so you have to prefix it with px.

like image 147
Bjarke Handsdal Avatar answered Feb 14 '26 11:02

Bjarke Handsdal


Viewport height and width can be accessed using:

width = window.innerWidth
height = window.innerHeight
like image 21
adalal Avatar answered Feb 14 '26 11:02

adalal