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
Related
Trying to get my application to fit into the browser window both width and height keeping proportions.
I have included a JS fiddle of an example: http://jsfiddle.net/4Mjtr/3/
Was sliced in photoshop so the way the html is output is each div class has its own css e.g
//HTML//
<div class="id1462-Select-Pattern">
<img src="http://www.travel-master.co.uk/coach-hire-minibus-images/email-quote.jpg"width="183" height="45" alt="" />
</div>
//CSS//
div.id1462-Select-Pattern {
position:absolute;
left:80px;
top:723px;
width:183px;
height:45px;
}
I have tried media queries but the canvas and images dont seem to resize also i read that with text you have to manually change the font size but the images are not resizing properly
Remove the Height from the image, setting only the width will resize the image and keep proportions as well.
You can use javascript function to get the browser's Width & Height, would be something like:
function getBrowserWindowSize() {
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;
}
var currWindow = new Array();
currWindow[0] = myWidth;
currWindow[1] = myHeight;
return currWindow;
}
And you can manage your desired elements width & height with the resize and load events by calling this function again.
I need a Js / JQuery Script , which return me browser's available width and height excluding menu bar and toolbar size , i am using one script but it seems to be returning width / height including toolbar ect...
below is script i have used..
<script type="text/javascript" >
var winWidth = 0, winHeight = 0;
if (typeof (window.innerWidth) == 'number') {
//Non-IE
winWidth = window.innerWidth;
winHeight = window.innerHeight;
} else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
//IE 6+ in 'standards compliant mode'
winWidth = document.documentElement.clientWidth;
winHeight = document.documentElement.clientHeight;
} else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
//IE 4 compatible
winWidth = document.body.clientWidth;
winHeight = document.body.clientHeight;
}
</script>
Any body have any clue on this?
Thanks
Meghana
Using jQuery , you can have the following :
$(window).height(); // returns height of browser viewport
$(document).height(); // returns height of HTML document
Your code should return the usable size of your browser window. In my case, on a 1920x1200 display, I get 1920x1106. My taskbar is 40 pixels tall, so that leaves 54px for the titlebar of the window.
try:
<input type='button' id='btn1' value='test'/>
$('#btn1').click(function(){
alert($(window).width());
});
See http://jsfiddle.net/Pu2Ej/
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'm trying to work out how to enlarge all elements on a page, but keep the centre of enlargement in the centre of the window.
On this page, once the image reaches the top or the left side of the window the centre of enlargement changes. It also changes when you move the image. (exactly what you would expect)
I'm thinking I'd need to take a completely different approach to achieve what I want. But I'm not sure what that approach is..
Any ideas?
Well, here's my take.
Only thing is that I ditched the containers you were using. Is that cheating? Seems like they were only there to get the image centered. No need.
This works as expected with no side effects.
Here's a working demo you can test:
http://jsfiddle.net/YFPRB/1/
(You need to click on the pane with the baboon first.)
HTML
<body>
<img src="http://cdn.sstatic.net/stackoverflow/img/apple-touch-icon.png" />
</body>
CSS
html, body {
width: 100%;
height: 100%;
overflow: hidden;
}
jQuery
EDIT: Thanks to #stagas for the reminder to clean up redundancies.
var $img = $('img'); // Cache the image. Better for performance.
$img.draggable();
$img.css({left: ($('body').width() / 2) - ($img.width() / 2)})
.css({top: ($('body').height() / 2) - ($img.height() / 2)})
$(document).keydown(function(event) {
if (event.keyCode == 38) {
var adjustment = 1.25;
} else if (event.keyCode == 40) {
var adjustment = 0.8;
} else {
return;
}
var offset = $img.offset();
var width = $img.width();
var height = $img.height();
var newWidth = width * adjustment;
var newHeight = height * adjustment;
var diffWidth = newWidth - width;
var diffHeight = newHeight - height;
var hcenter = $('body').width() / 2;
var vcenter = $('body').height() / 2;
var leftPercent = (hcenter - offset.left) / width;
var topPercent = (vcenter - offset.top) / height;
$img.offset({top: offset.top - (diffHeight * topPercent), left: offset.left - (diffWidth * leftPercent)});
$img.width(newWidth).height(newHeight);
});
This is what I came up, it works as you say except the image will always go to the center after zooming in or out:
$('document').ready(function() {
zoomimg=$('#zoomimg'); // we store this in a variable since we don't need to traverse the DOM every time -- this is faster
var viewportWidth = $(window).width();
var viewportHeight = window.innerHeight ? window.innerHeight : $(window).height(); // this is to work with Opera
zoomimg.css({'position': 'absolute', 'left': (viewportWidth/2)-(zoomimg.width()/2), 'top' : (viewportHeight/2)-(zoomimg.height()/2)}).draggable();
$(document).keydown(function(event) {
event = event || window.event;
var viewportWidth = $(window).width();
var viewportHeight = window.innerHeight ? window.innerHeight : $(window).height(); // this is to work with Opera
if (event.keyCode == 38) {
width = zoomimg.width();
height = zoomimg.height();
zoomimg.width(width*1.2).height(height*1.2);
var viewportWidth = $(window).width();
var viewportHeight = window.innerHeight ? window.innerHeight : $(window).height();
zoomimg.css({'left': (viewportWidth/2)-(zoomimg.width()/2), 'top' : (viewportHeight/2)-(zoomimg.height()/2)});
} else if (event.keyCode == 40) {
width = zoomimg.width();
height = zoomimg.height();
zoomimg.width(width*0.8).height(height*0.8);
var viewportWidth = $(window).width();
var viewportHeight = window.innerHeight ? window.innerHeight : $(window).height();
zoomimg.css({'left': (viewportWidth/2)-(zoomimg.width()/2), 'top' : (viewportHeight/2)-(zoomimg.height()/2)});
} else {
return
}
});
});
You should put an ID 'zoomimg' on the tag for it to work, and overflow:hidden on the #container . Also ditch that display:table and display:table-cell they're useless now that we center with Javascript. Also, pressing the down arrow key will cause the container to scroll down, so you should use other keys, as the arrows are reserved by the browser for scrolling the viewport.
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() );