i used screen.width to get the width of the browser. it worked fine with iphone safari but didn't work in android phone(it showed 800 width for android browser).
Is there any compatible way to get the screen width. I dont want to use UserAgent to check if its mobile browser. would like to use a javascript for that and logic should include screen width.
It's know issue - see here
When page first loads the screen.width and screen.height are wrong.
Try a timeout like this:
setTimeout(CheckResolution, 300);
Where CheckResolution is your function.
You may try this url for detect screen size and apply a CSS style
or
<script type="text/javascript">
function getWidth()
{
xWidth = null;
if(window.screen != null)
xWidth = window.screen.availWidth;
if(window.innerWidth != null)
xWidth = window.innerWidth;
if(document.body != null)
xWidth = document.body.clientWidth;
return xWidth;
}
function getHeight() {
xHeight = null;
if(window.screen != null)
xHeight = window.screen.availHeight;
if(window.innerHeight != null)
xHeight = window.innerHeight;
if(document.body != null)
xHeight = document.body.clientHeight;
return xHeight;
}
</script>
screen.height shows the height of the screen
screen.width shows the width of the screen
screen.availHeight shows height but removes the interface height like taskbar, and browser menu etc.
screen.availWidth same as above,instead gives available width
For those interested in getting the width values of the browser, I tested several options:
I am using bootstrap 3 and the ONLY solution matching the bootstrap 3 breakpoints with both IE and Chrome was :
window.innerWidth
Here are the results with 1200px window with:
Chrome
$( window ).width(): 1183
$( document ).width():1183
screen.width: 1536
$( window ).innerWidth():1183
$( document ).innerWidth():1183
window.innerWidth: 1200
$( document ).outerWidth():1183
window.outerWidth: 1216
document.documentElement.clientWidth: 1183
Internet Explorer 10
$( window ).width(): 1200
$( document ).width():1200
screen.width: 1536
$( window ).innerWidth():1200
$( document ).innerWidth():1200
window.innerWidth: 1200
$( document ).outerWidth():1200
window.outerWidth: 1214
document.documentElement.clientWidth: 1200
Just read these two URLs. It should help you get what you need.
http://www.quirksmode.org/blog/archives/2010/08/combining_media.html
http://www.quirksmode.org/mobile/tableViewport.html
FYI, the Android probably is 800px wide. See this article among others:
Understanding Samsung Galaxy Tab screen density
Edit: Oh, I think the other guy was righter than me that pointed to the Android bug.
I find that using window.outerWidth gives the correct value. Tested this using BrowserStack android emulators.
Related
I'm trying to get the screen width of user device using window.screen.width. This method is working fine on most of the devices but not on iPad. When the iPad is in portrait mode, the screen width is shown to be 768px and height to be 1024px(using window.screen.height).All good till now. But the width and height remains the same in landscape mode too. In other devices, the "width*height" value switches when orientation changes and all my calculations was based on that concept.
Alternative solution using
window.innerWidth
window.innerHeight
will work perfect if your webview fill you ios ViewController
and will give you correct values even when you change the orientation while application is running..
That screen.availWidth & screen.availHeight give you the correct values only at first run before change the iPad orientation
Instead of using screen.width use the below one:
var body = document.body;
if(body.scrollWidth < 1024){
//code here
}
if(body.scrollWidth < 768){
//code here
}
if(body.scrollWidth == 1024){
//code here
}
if(body.scrollWidth <= 1024){
//code here
}
I'm working on a web app that is targeted to browsers on desktop, tablet and smartphone.
The web app has a light box implemented using Colorbox with an iframe. When the browser window is resized or the tablet/phone has it's orientation changed, Javascript code queries the window dimensions so that it can resize some elements of the light box.
The issue I'm having is that everything works fine on desktop (Windows: IE, Firefox, Chrome, Mac: Safari), iPad & iPhone but not on the Android smartphone (HTC) and Android Emulator.
Android always returns different values for screen.width, screen.height, window.innerWidth & window.innerHeight when they're queried from inside the window's resize event, which fires multiple times.
Why is the Android browser returning such a wide variance in values and how can I reliably detect the width and height of the browser window?
On Android, window.outerWidth and window.outerHeight are reliably the screen size. Depending on your version of Android, innerWidth/Height is usually incorrect.
Here's a really good writeup on the situation.
Below is differentiation based on readings with Samsung Tab running Android 4.1
screen.height - gives actual device height including task bar and
title bar
window.innerHeight - gives the height excluding task bar, title bar
and address bar(if visible)
window.outerHeight - gives the height excluding task bar and title
bar height, (no matter address bar is visible or hidden, outerHeight
include the address bar height.)
I took me hours to find a workaround.
The only constant among window.innerHeight, window.outerheight, etc was screen.height.
This code gave me the outerheight:
screen.height / window.devicePixelRatio - window.screenTop
Also, in order to support older versions of android, place your code in a setTimeout
I hope this is helpful =)
I'm using this to make it work between ios and android.
var screenHeight = (ionic.Platform.isIOS()) ? window.screen.height : window.innerHeight * window.devicePixelRatio;
Try this, and check your mobile reading
<script>
var total_height=screen.height*window.devicePixelRatio;
alert(total_height);
</script>
It should match the screen size (height) of your phone specifications.
var throttle = (function () {
var timer;
return function (fn, delay) {
clearTimeout(timer);
timer = setTimeout(fn, delay);
};
})(),
var callback = function (w, h) {
alert(w + ' ' + h);
}
window.onresize = throttle(function () {
width = Math.min(window.innerWidth, window.outerWidth);
height = Math.min(window.innerHeight, window.outerHeight);
callback(width, height);
}, 60);
Dan's answer fix the inconcistancy between android's browser..
so I post how I detect/change mobile viewport and adapt it when rotated
(don't know if usable for any one...
var lastorg=0; //set the begining of script
thisorg=parseInt(window.innerWidth)/parseInt(window.innerHeight); //for ratio to detact orietation
if(((lastorg<1 && thisorg>1) ||(lastorg>1 && thisorg<1) ||lastorg==0 )){ //is start or change
$("#viewport").attr('content', 'width=device-width, initial-scale=1,minimum-scale=1, maximum-scale=1'); // reset viewport to device
mywidth = Math.min(window.innerWidth, window.outerWidth); //Dan's way to fix the inconsistancy
myheight = Math.min(window.innerHeight, window.outerHeight);
lastorg=thisorg; //update the lastorg
wr=parseInt(mywidth)/1280; // the minimum desire width
hr=parseInt(myheight)/630; // the minimum desire height
if(hr<wr){
vscale=hr;
if(hr<1){ // if it if small screen, so desktop pc wouldn't change
windowHeight=630;
windowwidth=mywidth/hr;
}
}else{
vscale=wr;
if(wr<1){
windowwidth=1280;
windowHeight=myheight/wr;
}
}
$("#viewport").attr('content', 'width=device-width, initial-scale='+vscale+',minimum-scale='+vscale+', maximum-scale='+vscale); //reset viewport toresize window
if(thisorg>1){
$("#pro").fadeOut(500);
}else{
$("body").prepend("<div id=pro style='position:absolute;width:800px;height:30px;padding:30px;left:"+(windowwidth/2)+"px;top:"+(windowHeight/2)+"px;margin-left:-430px;margin-top:-45px;;border:1px solid #555;background:#ddeeff;text-align:center;z-index:99999;color:#334455;font-size:40px;' class=shadowme>Please rotate your phone/tablet</div>");//tell user to rotate
}
}
In my case, the setTimeout hook was not useful.
After some digging, I discover that different Android versions (and devices) have different devicePixelRatio values.
If the devicePixelRatio is equal or greater than 1, the actual number of pixels in the screen (for the html page point of view) is given by window.screen.width (or ...height).
But, if the window.screen.width is less than 1 (it happens in some old Android devices), the actual number of pixels becomes: window.screen.width/devicePixelRatio.
So, you just have to cope with this.
w = window.screen.width;
h = window.screen.height;
if(window.devicePixelRatio < 1){
w = window.screen.width/window.devicePixelRatio;
h = window.screen.height/window.devicePixelRatio;
}
I'm trying to make my site mobile friendly.
I want to know the browser window size so that I do something when it's narrower than 728px and something else when it's bigger.
This must take into account resizing the window on the PC as well as changing from portrait to landscape mode in a phone.
How can this be done?
As m90 suggest, if the only thing you want to do is modify the style, then you should have a look at media queries. However, if you want to do more than just modify the style, then you have to rely on JavaScript.
Plain JavaScript
The problem is that it isn't entirely straight forward to get the width of the window, it varies between browsers. So you would have to create a function, something like this (untested):
var width = 0;
function updateWindowSize() {
if (document.body && document.body.offsetWidth) {
width = document.body.offsetWidth;
}
if (document.compatMode=='CSS1Compat' &&
document.documentElement &&
document.documentElement.offsetWidth ) {
width = document.documentElement.offsetWidth;
}
if (window.innerWidth) {
width = window.innerWidth;
}
}
Then you could listen for for the window onresize event, and call the function to get the new window size everytime the window changes.
window.onresize = function(event) {
updateWindowSize();
}
jQuery
If you use jQuery, then this can be done a bit shorter, as jQuery takes care of the cross-browser-support for you behind the scenes:
var width;
$(window).resize(function() {
width = $(window).width();
});
As a warning, IE8 and lower don't support media queries or CSS3. If you don't care about IE8, go for it. Respond.js, Modernizr and others can help to support IE6-8, but it's far from perfect.
How to get document height and width in pure javascript i.e without using jquery.
I know about $(document).height() and $(document).width(), but I want to do this in javascript.
I meant page's height and width.
var height = document.body.clientHeight;
var width = document.body.clientWidth;
Check: this article for better explanation.
Even the last example given on http://www.howtocreate.co.uk/tutorials/javascript/browserwindow is not working on Quirks mode. Easier to find than I thought, this seems to be the solution(extracted from latest jquery code):
Math.max(
document.documentElement["clientWidth"],
document.body["scrollWidth"],
document.documentElement["scrollWidth"],
document.body["offsetWidth"],
document.documentElement["offsetWidth"]
);
just replace Width for "Height" to get Height.
This is a cross-browser solution:
var w = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
var h = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
You should use getBoundingClientRect as it usually works cross browser and gives you sub-pixel precision on the bounds rectangle.
elem.getBoundingClientRect()
Get document size without jQuery
document.documentElement.clientWidth
document.documentElement.clientHeight
And use this if you need Screen size
screen.width
screen.height
You can try also:
document.body.offsetHeight
document.body.offsetWidth
This should work for all browsers/devices:
function getActualWidth()
{
var actualWidth = window.innerWidth ||
document.documentElement.clientWidth ||
document.body.clientWidth ||
document.body.offsetWidth;
return actualWidth;
}
If you want to get the full width of the page, including overflow, use document.body.scrollWidth.
window is the whole browser's application window. document is the webpage shown that is actually loaded.
window.innerWidth and window.innerHeight will take scrollbars into account which may not be what you want.
document.documentElement is the full webpage without the top scrollbar. document.documentElement.clientWidth returns document width size without y scrollbar.
document.documentElement.clientHeight returns document height size without x scrollbar.
How to find out the document width and height very easily?
in HTML
<span id="hidden_placer" style="position:absolute;right:0;bottom:0;visibility:hidden;"></span>
in javascript
var c=document.querySelector('#hidden_placer');
var r=c.getBoundingClientRect();
r.right=document width
r.bottom=document height`
You may update this on every window resize event, if needed.
Depending on which mode of IE8 i'm in (quirks or standard) i get different values for the height and width. I've tried standard javascript and jquery but both return different results.
In Quirks
$('body').width = 1239
$('body').height = 184
document.body.clientWidth = 1231
document.body.clientHeight = 176
In standards
$('body').width = 1260
$('body').height = 182
document.body.clientWidth = 1254
document.body.clientHeight = 176
Any ideas how to get a value unchanged by the mode of IE8.
Thanks in adv.
Perhaps the issue is due to the scrollbars being included in the width and height regardless of whether or not they are there. I don't have IE (on a mac) so can't verify.
However, I can tell you what does work as in my project jQuery Lightbox I have no such issue. We use the following code in it:
// Make the overlay the size of the body
var $body = $(this.ie6 ? document.body : document); // using document in ie6 causes a crash
$('#lightbox-overlay').css({
width: $body.width(),
height: $body.height()
});
// ... some code ...
// Get the window dimensions
var $window = $(window);
var wWidth = $window.width();
var wHeight = $window.height();
And the overlay displays correctly. I would trust jQuery's result of the width and height compared to that of the native result, as jQuery should naturally be taking into account any quirks with the browser.
It is important to note that the lightbox script above tends to prefer $(document) over $(document.body) for some reason - I can't remember sorry :O - so perhaps this solves the issue as well?
Just a quickshot. Try to give your body #page:
function getPageHeight() {
var pageHeight = document.getElementById('page').offsetHeight;
var pageWidth = document.getElementById('page').offsetWidth;
alert(pageHeight);
alert(pageWidth);
}
Try this:
var viewport = {
width : $(window).width(),
height : $(window).height()
};
var width = viewport.width;
var height = viewport.height;