I am trying to write a JavaScript function to get the current browser width.
I found this one:
console.log(document.body.offsetWidth);
But its problem that it fail if the body has width 100%.
Is there any other better function or a workaround?
It's a pain in the ass. I recommend skipping the nonsense and using jQuery, which lets you just do $(window).width().
Update for 2017
My original answer was written in 2009. While it still works, I'd like to update it for 2017. Browsers can still behave differently. I trust the jQuery team to do a great job at maintaining cross-browser consistency. However, it's not necessary to include the entire library. In the jQuery source, the relevant portion is found on line 37 of dimensions.js. Here it is extracted and modified to work standalone:
function getWidth() {
return Math.max(
document.body.scrollWidth,
document.documentElement.scrollWidth,
document.body.offsetWidth,
document.documentElement.offsetWidth,
document.documentElement.clientWidth
);
}
function getHeight() {
return Math.max(
document.body.scrollHeight,
document.documentElement.scrollHeight,
document.body.offsetHeight,
document.documentElement.offsetHeight,
document.documentElement.clientHeight
);
}
console.log('Width: ' + getWidth() );
console.log('Height: ' + getHeight() );
Original Answer
Since all browsers behave differently, you'll need to test for values first, and then use the correct one. Here's a function that does this for you:
function getWidth() {
if (self.innerWidth) {
return self.innerWidth;
}
if (document.documentElement && document.documentElement.clientWidth) {
return document.documentElement.clientWidth;
}
if (document.body) {
return document.body.clientWidth;
}
}
and similarly for height:
function getHeight() {
if (self.innerHeight) {
return self.innerHeight;
}
if (document.documentElement && document.documentElement.clientHeight) {
return document.documentElement.clientHeight;
}
if (document.body) {
return document.body.clientHeight;
}
}
Call both of these in your scripts using getWidth() or getHeight(). If none of the browser's native properties are defined, it will return undefined.
var w = window.innerWidth;
var h = window.innerHeight;
var ow = window.outerWidth; //including toolbars and status bar etc.
var oh = window.outerHeight;
Both return integers and don't require jQuery. Cross-browser compatible.
I often find jQuery returns invalid values for width() and height()
Why nobody mentions matchMedia?
if (window.matchMedia("(min-width: 400px)").matches) {
/* the viewport is at least 400 pixels wide */
} else {
/* the viewport is less than 400 pixels wide */
}
Did not test that much, but tested with android default and android chrome browsers, desktop chrome, so far it looks like it works well.
Of course it does not return number value, but returns boolean - if matches or not, so might not exactly fit the question but that's what we want anyway and probably the author of question wants.
From W3schools and its cross browser back to the dark ages of IE!
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var w = window.innerWidth
|| document.documentElement.clientWidth
|| document.body.clientWidth;
var h = window.innerHeight
|| document.documentElement.clientHeight
|| document.body.clientHeight;
var x = document.getElementById("demo");
x.innerHTML = "Browser inner window width: " + w + ", height: " + h + ".";
alert("Browser inner window width: " + w + ", height: " + h + ".");
</script>
</body>
</html>
Here is a shorter version of the function presented above:
function getWidth() {
if (self.innerWidth) {
return self.innerWidth;
}
else if (document.documentElement && document.documentElement.clientHeight){
return document.documentElement.clientWidth;
}
else if (document.body) {
return document.body.clientWidth;
}
return 0;
}
An important addition to Travis' answer; you need to put the getWidth() up in your document body to make sure that the scrollbar width is counted, else scrollbar width of the browser subtracted from getWidth(). What i did ;
<body>
<script>
function getWidth(){
return Math.max(document.body.scrollWidth,
document.documentElement.scrollWidth,
document.body.offsetWidth,
document.documentElement.offsetWidth,
document.documentElement.clientWidth);
}
var aWidth=getWidth();
</script>
</body>
and call aWidth variable anywhere afterwards.
An adapted solution to modern JS of Travis' answer:
const getPageWidth = () => {
const bodyMax = document.body
? Math.max(document.body.scrollWidth, document.body.offsetWidth)
: 0;
const docElementMax = document.documentElement
? Math.max(
document.documentElement.scrollWidth,
document.documentElement.offsetWidth,
document.documentElement.clientWidth
)
: 0;
return Math.max(bodyMax, docElementMax);
};
function getWidth() {
return Math.max(
document.body.scrollWidth,
document.documentElement.scrollWidth,
document.body.offsetWidth,
document.documentElement.offsetWidth,
document.documentElement.clientWidth
);
}
function getHeight() {
return Math.max(
document.body.scrollHeight,
document.documentElement.scrollHeight,
document.body.offsetHeight,
document.documentElement.offsetHeight,
document.documentElement.clientHeight
);
}
console.log('Width: ' + getWidth() );
console.log('Height: ' + getHeight() );
Related
How can I find out what percentage of the vertical scrollbar a user has moved through at any given point?
It's easy enough to trap the onscroll event to fire when the user scrolls down the page, but how do I find out within that event how far they have scrolled? In this case, the percentage particularly is what's important. I'm not particularly worried about a solution for IE6.
Do any of the major frameworks (Dojo, jQuery, Prototype, Mootools) expose this in a simple cross-browser compatible way?
Oct 2016: Fixed. Parentheses in jsbin demo were missing from answer. Oops.
Chrome, Firefox, IE9+. Live Demo on jsbin
var h = document.documentElement,
b = document.body,
st = 'scrollTop',
sh = 'scrollHeight';
var percent = (h[st]||b[st]) / ((h[sh]||b[sh]) - h.clientHeight) * 100;
As function:
function getScrollPercent() {
var h = document.documentElement,
b = document.body,
st = 'scrollTop',
sh = 'scrollHeight';
return (h[st]||b[st]) / ((h[sh]||b[sh]) - h.clientHeight) * 100;
}
If you prefer jQuery (original answer):
$(window).on('scroll', function(){
var s = $(window).scrollTop(),
d = $(document).height(),
c = $(window).height();
var scrollPercent = (s / (d - c)) * 100;
console.clear();
console.log(scrollPercent);
})
html{ height:100%; }
body{ height:300%; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I think I found a good solution that doesn't depend on any library:
/**
* Get current browser viewpane heigtht
*/
function _get_window_height() {
return window.innerHeight ||
document.documentElement.clientHeight ||
document.body.clientHeight || 0;
}
/**
* Get current absolute window scroll position
*/
function _get_window_Yscroll() {
return window.pageYOffset ||
document.body.scrollTop ||
document.documentElement.scrollTop || 0;
}
/**
* Get current absolute document height
*/
function _get_doc_height() {
return Math.max(
document.body.scrollHeight || 0,
document.documentElement.scrollHeight || 0,
document.body.offsetHeight || 0,
document.documentElement.offsetHeight || 0,
document.body.clientHeight || 0,
document.documentElement.clientHeight || 0
);
}
/**
* Get current vertical scroll percentage
*/
function _get_scroll_percentage() {
return (
(_get_window_Yscroll() + _get_window_height()) / _get_doc_height()
) * 100;
}
This should do the trick, no libraries required:
function currentScrollPercentage()
{
return ((document.documentElement.scrollTop + document.body.scrollTop) / (document.documentElement.scrollHeight - document.documentElement.clientHeight) * 100);
}
These worked for me perfectly in Chrome 19.0, FF12, IE9:
function getElementScrollScale(domElement){
return domElement.scrollTop / (domElement.scrollHeight - domElement.clientHeight);
}
function setElementScrollScale(domElement,scale){
domElement.scrollTop = (domElement.scrollHeight - domElement.clientHeight) * scale;
}
A Typescript implementation.
function getScrollPercent(event: Event): number {
const {target} = event;
const {documentElement, body} = target as Document;
const {scrollTop: documentElementScrollTop, scrollHeight: documentElementScrollHeight, clientHeight} = documentElement;
const {scrollTop: bodyScrollTop, scrollHeight: bodyScrollHeight} = body;
const percent = (documentElementScrollTop || bodyScrollTop) / ((documentElementScrollHeight || bodyScrollHeight) - clientHeight) * 100;
return Math.ceil(percent);
}
If you're using Dojo, you can do the following:
var vp = dijit.getViewport();
return (vp.t / (document.documentElement.scrollHeight - vp.h));
Which will return a value between 0 and 1.
This question has been here for a long time, I know, but I stumbled onto it while trying to solve the same problem. Here is how I solved it, in jQuery:
First, I wrapped the thing I wanted to scroll in a div (not semantic, but it helps). Then set the overflow and height on the wrapper.
<div class="content-wrapper" style="overflow: scroll; height:100px">
<div class="content">Lot of content that scrolls</div>
</div>
Finally I was able to calculate the % scroll from these metrics:
var $w = $(this),
scroll_top = $w.scrollTop(),
total_height = $w.find(".content").height(),
viewable_area = $w.height(),
scroll_percent = Math.floor((scroll_top + viewable_area) / total_height * 100);
Here is a fiddle with working example: http://jsfiddle.net/prEGf/
Everyone has great answers, but I just needed an answer as one variable. I didn't need an event listener, I just wanted to get the scrolled percentage. This is what I got:
const scrolledPercentage =
window.scrollY / (document.documentElement.scrollHeight - document.documentElement.clientHeight)
document.addEventListener("scroll", function() {
const height = window.scrollY / (document.documentElement.scrollHeight - document.documentElement.clientHeight)
document.getElementById("height").innerHTML = `Height: ${height}`
})
.container {
position: relative;
height: 200vh;
}
.sticky-div {
position: sticky;
top: 0;
}
<!DOCType>
<html>
<head>
</head>
<body>
<div id="container" class="container">
<div id="height" class="sticky-div">
Height: 0
</div>
</div>
</body>
First attach an event listener to some document you want to keep track
yourDocument.addEventListener("scroll", documentEventListener, false);
Then:
function documentEventListener(){
var currentDocument = this;
var docsWindow = $(currentDocument.defaultView); // This is the window holding the document
var docsWindowHeight = docsWindow.height(); // The viewport of the wrapper window
var scrollTop = $(currentDocument).scrollTop(); // How much we scrolled already, in the viewport
var docHeight = $(currentDocument).height(); // This is the full document height.
var howMuchMoreWeCanScrollDown = docHeight - (docsWindowHeight + scrollTop);
var percentViewed = 100.0 * (1 - howMuchMoreWeCanScrollDown / docHeight);
console.log("More to scroll: "+howMuchMoreWeCanScrollDown+"pixels. Percent Viewed: "+percentViewed+"%");
}
My two cents, the accepted answer in a more "modern" way. Works back to IE9 using #babel/preset-env.
// utilities.js
/**
* #param {Function} onRatioChange The callback when the scroll ratio changes
*/
export const monitorScroll = onRatioChange => {
const html = document.documentElement;
const body = document.body;
window.addEventListener('scroll', () => {
onRatioChange(
(html.scrollTop || body.scrollTop)
/
((html.scrollHeight || body.scrollHeight) - html.clientHeight)
);
});
};
Usage:
// app.js
import { monitorScroll } from './utilities';
monitorScroll(ratio => {
console.log(`${(ratio * 100).toFixed(2)}% of the page`);
});
I reviewed all of these up there but they use more complex approaches to solve. I found this through a mathematical formula; brief.
The formula goes Value/Total * 100. Say Total is 200 u wanna know the percentage of 100 out of 200, you do it 100/200 * 100% = 50% (the value)
pageYOffset = The vertical scroll count without including borders. When you scroll down to bottom you get the maximum count.
offsetHeight = The total height of the page including borders!
clientHeight = The height in pixels without borders but not to the end of content!
When u scroll to bottom u get pageyoffset of 1000 for example, whereas offsetHeight of 1200 and clientHeight of 200. 1200 - 200(clientheight) now u get paggeYOffset value in offsetHeight and so scrollPosition300(300 of 1000)/1000 * 100 = 30%.
`pageOffset = window.pageYOffset;
pageHeight = document.documentElement.offsetHeight;
clientHeight = document.documentElement.clientHeight;
percentage = pageOffset / (pageHeight - clientHeight) * 100 + "%";
console.log(percentage)`
The reason why we must do offsetHeight - clientHeight it is because client heights shows all the available content in px without borders, and offsetheight shows the available content including borders, whereas pageYOffset counts the scrolls made; The scrollbar is quite long to count the whole windows it counts the scrolls itself until reaches the end, the available space in scrollbar is in px pageYOffset, so to reach that number you substract offsetHeight - clientHeight to bring to the lower value of pageYOffset.
i'll update when i get on pc, please leave a comment to make it clear so i don't forget! Thanks :)
Using jQuery
$(window).scrollTop();
will get you the scroll position, you can then work out from there what the percentage is based on the window height.
There is also a standard DOM property scrollTop that you can use like document.body.scrollTop however I'm not sure how this behaves cross-browser, I would assume if there are inconsistencies then the jQuery method accounts for these.
var maxScrollTop = messages.get(0).scrollHeight - messages.height();
var scroll = messages.scrollTop() / maxScrollTop; // [0..1]
I found a way to correct a previous answer, so it works in all cases. Tested on Chrome, Firefox and Safari.
(((document.documentElement.scrollTop + document.body.scrollTop) / (document.documentElement.scrollHeight - document.documentElement.clientHeight) || 0) * 100)
I have fullscreen site. When I click to my page, image resize fullscreen directly. It's working on IE 9-10, Chrome, Firefox. But don't working on IE8.
My JS code:
$(window).resize(function () {
$("#backgrounds img").each(function (k, v) {
$backgroundImg = $(this);
windowWidth = window.innerWidth
windowHeight = window.innerHeight
imageWidth = 1366
imageHeight = 900
widthRatio = windowWidth / imageWidth;
heightRatio = windowHeight / imageHeight;
console.log('width: ' + widthRatio)
console.log('height: ' + heightRatio)
if (widthRatio > heightRatio) {
$backgroundImg.width(windowWidth);
$backgroundImg.height(imageHeight * widthRatio);
} else {
$backgroundImg.height(windowHeight);
$backgroundImg.width(imageWidth * heightRatio);
}
$backgroundImg.css({ marginLeft: -$backgroundImg.width() / 2 });
$backgroundImg.css({ left: "50%" });
});
});
When I check e.g. console on Chrome, get this data:
width: 1.3711566617862372
height: 0.7488888888888889
But when I check this function on IE8, get this:
height: NaN
width: NaN
Searched on StackoverFlow but don't find solution. How can I fix it? Thank you.
The innerWidth is NOT supported by IE8 ,
Use this for all support ,
var windowWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
Yes, it's innerWidth support problem and solved by this link:
https://stackoverflow.com/a/18136089/1485921
So, added this function on my js file:
(function (window, html, body) {
if (!window.innerWidth) Object.defineProperty(window, 'innerWidth', {
get: function () { return html.clientWidth }
});
if (!window.innerHeight) Object.defineProperty(window, 'innerHeight', {
get: function () { return html.clientHeight }
});
}(this, document.documentElement, document.body));
Thank you!
I have made the body of the page 200% tall so that it fits on a screen twice. Using javascript I am making it keep scrolling to the top or bottom when you scroll. For this, I need to find out the lowest scroll point of the page on any browser or screen size so that it stops when it gets there.
No JQuery please.
Thank you.
My code: (it is still being put together so needs a bit of work)
function getScrollXY() {
var x = 0, y = 0;
if( typeof( window.pageYOffset ) == 'number' ) {
// Netscape
x = window.pageXOffset;
y = window.pageYOffset;
} else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
// DOM
x = document.body.scrollLeft;
y = document.body.scrollTop;
} else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
// IE6 standards compliant mode
x = document.documentElement.scrollLeft;
y = document.documentElement.scrollTop;
}
return [x, y];
}
function scrollup() {
if (xy[1] > 0) {
window.scrollBy(0,-100);
setTimeout(scrollup,200);
} else {
null;
}
}
function scrolldown() {
if (xy[1] < ) {
window.scrollBy(0,100);
setTimeout(scrolldown,200);
} else {
null;
}
}
function dothescroll() {
var xy = getScrollXY();
var y = xy[1];
setTimeout(function(){
if (xy[1] > y) {
scrollup();
} else {
scrolldown();
}
},200);
}
This is the cross browser compatible version:
var limit = Math.max( document.body.scrollHeight, document.body.offsetHeight,
document.documentElement.clientHeight, document.documentElement.scrollHeight, document.documentElement.offsetHeight );
While this is not part of any specification, you could try window.scrollMaxY.
Returns the maximum number of pixels that the document can be scrolled vertically.
https://developer.mozilla.org/docs/Web/API/Window/scrollMaxY
Fallback if unavailable:
var scrollMaxY = window.scrollMaxY || (document.documentElement.scrollHeight - document.documentElement.clientHeight)
Note, documentElement isn't always the scrolling element (some browsers use body instead). The solution is the new scrollingElement property, which returns a reference to the Element that scrolls the document. It is specified, but still a working draft.
var limit = document.body.offsetHeight - window.innerHeight;
// document.body.offsetHeight = computed height of the <body>
// window.innerHeight = available vertical space in the window
Compare xy[1] < limit
Note: You might need to increase the value by margin and/or padding of the body. You can also try using clientHeight instead of offsetHeight.
My solution based on the solutions above and what I use in 2022.
AKA scrollMaxY
const scrollMaxValue = () => {
const body = document.body;
const html = document.documentElement;
const documentHeight = Math.max(
body.scrollHeight,
body.offsetHeight,
html.clientHeight,
html.scrollHeight,
html.offsetHeight
);
const windowHeight = window.innerHeight;
return documentHeight - windowHeight;
};
scrollMaxValue()
window.scrollTo(0, document.body.scrollHeight);
this will work..
In html head:
<script type="text/javascript">
var myWidth = 0, myHeight = 0;
if( typeof( window.innerWidth ) == 'number' ) {
myWidth = window.innerWidth; myHeight = window.innerHeight;
} else if( document.documentElement && ( document.documentElement.clientWidth ||document.documentElement.clientHeight ) ) {
myWidth = document.documentElement.clientWidth; myHeight = document.documentElement.clientHeight;
} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
myWidth = document.body.clientWidth; myHeight = document.body.clientHeight;
}
</script>
In html body:
<script type="text/javascript">
document.write('<p>' + myWidth + 'x' + myHeight + '</p>');
</script>
It works good. The question is: how can I have it to display the width/height values while resizing the browser? Like here http://quirktools.com/screenfly/ at bottom left corner.
Many thanks!
I like gilly3's solution, but it would be useful to have the full code (for those in a hurry!)
<script>
window.onresize = displayWindowSize;
window.onload = displayWindowSize;
function displayWindowSize() {
myWidth = window.innerWidth;
myHeight = window.innerHeight;
// your size calculation code here
document.getElementById("dimensions").innerHTML = myWidth + "x" + myHeight;
};
</script>
Bind to window.onresize. Don't use document.write(). Put the <p> in your HTML and give it an id. Then just set the innerHTML of the element directly:
window.onresize = displayWindowSize;
window.onload = displayWindowSize;
function displayWindowSize() {
// your size calculation code here
document.getElementById("dimensions").innerHTML = myWidth + "x" + myHeight;
};
Or, if you're already using jquery, you can use .resize(handler) to capture the resize event and .resize() without any parameters to trigger the initial event when the window is done loading.
Like this:
$(window).resize(function() {
// your size calculation code here
$("#dimensions").html(myWidth);
}).resize();
Demo in Fiddle
<!DOCTYPE html>
<html>
<head>
<title>How to get width of screen when window is resizing?</title>
</head>
<body>
<script>
window.onresize=function()
{
document.body.innerHTML=window.innerWidth;
}
</script>
</body>
</html>
To learn the meaning of the each line of the code - https://jaischool.com/javascript-lang/how-to-get-live-width-of-window-when-it-is-resizing.html
I am looking for a code snippet to get the height of the viewable area within a browser window.
I had this code, however it is somewhat bugged as if the the body doesn't exceed the height the of the window then it comes back short.
document.body.clientHeight;
I have tried a couple of other things but they either return NaN or the same height as the above.
Does anyone know how to get the real height of the browsing window?
You'll want something like this, taken from http://www.howtocreate.co.uk/tutorials/javascript/browserwindow
function alertSize() {
var myWidth = 0, myHeight = 0;
if( typeof( window.innerWidth ) == 'number' ) {
//Non-IE
myWidth = window.innerWidth;
myHeight = window.innerHeight;
} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
//IE 6+ in 'standards compliant mode'
myWidth = document.documentElement.clientWidth;
myHeight = document.documentElement.clientHeight;
} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
//IE 4 compatible
myWidth = document.body.clientWidth;
myHeight = document.body.clientHeight;
}
window.alert( 'Width = ' + myWidth );
window.alert( 'Height = ' + myHeight );
}
So that's innerHeight for modern browsers, documentElement.clientHeight for IE, body.clientHeight for deprecated/quirks.
Try using jquery:
window_size = $(window).height();
You can use the window.innerHeight
The way that I like to do it is like this with a ternary assignment.
var width = isNaN(window.innerWidth) ? window.clientWidth : window.innerWidth;
var height = isNaN(window.innerHeight) ? window.clientHeight : window.innerHeight;
I might point out that, if you run this in the global context that from that point on you could use window.height and window.width.
Works on IE and other browsers as far as I know (I have only tested it on IE11).
Super clean and, if I am not mistaken, efficient.
There's a simpler way than a whole bunch of if statements. Use the or (||) operator.
function getBrowserDimensions() {
return {
width: (window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth),
height: (window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight)
};
}
var browser_dims = getBrowserDimensions();
alert("Width = " + browser_dims.width + "\nHeight = " + browser_dims.height);
This should works too. First create an absolute <div> element with absolute position and 100% height:
<div id="h" style="position:absolute;top:0;bottom:0;"></div>
Then, get the window height from that element via offsetHeight
var winHeight = document.getElementById('h').offsetHeight;
Update:
function getBrowserSize() {
var div = document.createElement('div');
div.style.position = 'absolute';
div.style.top = 0;
div.style.left = 0;
div.style.width = '100%';
div.style.height = '100%';
document.documentElement.appendChild(div);
var results = {
width: div.offsetWidth,
height: div.offsetHeight
};
div.parentNode.removeChild(div); // remove the `div`
return results;
}
console.log(getBrowserSize());
var winWidth = window.screen.width;
var winHeight = window.screen.height;
document.write(winWidth, winHeight);
With JQuery you can try this $(window).innerHeight() (Works for me on Chrome, FF and IE). With bootstrap modal I used something like the following;
$('#YourModal').on('show.bs.modal', function () {
$('.modal-body').css('height', $(window).innerHeight() * 0.7);
});
I prefer the way I just figured out... No JS... 100% HTML & CSS:
(Will center it perfectly in the middle, regardless of the content size.
HTML FILE
<html><head>
<link href="jane.css" rel="stylesheet" />
</head>
<body>
<table id="container">
<tr>
<td id="centerpiece">
123
</td></tr></table>
</body></html>
CSS FILE
#container{
border:0;
width:100%;
height:100%;
}
#centerpiece{
vertical-align:middle;
text-align:center;
}
for centering images / div's held within the td, you may wish to try margin:auto; and specify a div dimension instead. -Though, saying that... the 'text-align' property will align much more than just a simple text element.
JavaScript version in case if jQuery is not an option:
window.screen.availHeight