innerWidth not getting the correct width on mobile - javascript

I have a code below that tries to determine whether someone is accessing my site from a mobile or desktop, by the innerWidth of their device. However, when I tried to get the innerWidth from my mobile, it shows that the width of my mobile is 980px? There's no way the width of my mobile is anywhere near that wide though. The width of my mobile is around: 300px, and the height is around 500px. On, my desktop though, it shows 1280px, which is correct. My questions is, why is it showing the wrong width for my mobile? Unless there's something I'm not understanding correctly?
<?php
include("ajaxLink.php");
?>
<script>
$(function(){
var width = window.innerWidth;
alert(width);
if (width > 500) {
alert("going to index");
window.location = "/";
} //end of if (width > 500)
else {
alert("going to mobile");
window.location = "mobile.php";
} //end of else (width <= 500)
});
</script>

window.innerWidth represents viewport pixels on most mobile devices and not physical pixels. You should be able to get around this through clever use of doctype declaration (such as.. actually declaring a doctype) as well as including a meta viewport tag in a head section. Here's a quote from this article that goes into detail about your specific question:
But when the viewport has not been constrained, and an HTML5 doctype (or none at all) is used, innerWidth will suddenly start to represent values much larger than the physical screen: and represent the width of the viewport canvas upon which the page has been rendered.
On a portrait iPhone, for example, the default viewport is 980 pixels. On a landscape iPhone it is, well, according to window.innerWidth, 981 (yes, really).
I would try this:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
</head>
According to quirksmode, window.outerWidth also jumps from being actual pixels to viewport pixels when zooming.

Related

React Page Getting Weird Scaling in Responsive Mode [duplicate]

When in google chrome's device mode, what does window.innerWidth return? Is it the viewport of the device (plus any scroll bars)?
I'm getting different values for the device's width x height (the dimensions on top of the page - the device's viewport?) and window.innerWidth x window.innerHeight (browser's viewport?). Is this supposed to happen?
Here's a picture of what I'm getting, and the code I used.
<!doctype html>
<html>
<head></head>
<body>
<script>
var image;
window.onload = function() {
image = document.getElementById("img");
checkWindowSize();
window.addEventListener('resize', function(event){
checkWindowSize();
});
}
function checkWindowSize() {
var width = window.innerWidth,
height = window.innerHeight;
console.log("window.innerHeight: ", window.innerHeight, " window.innerWidth: ", window.innerWidth);
}
</script>
<img id="img" class="vid-img-filter" src="http://i.imgur.com/jkhFJMn.jpg" alt="">
</body>
</html>
window.innerWidth and innerHeight return the dimensions of the visual viewport. In desktop browsers, this is generally the browser's window dimensions. On mobile the situation is a bit more complicated because of pinch zoom.
When you load a page without a <meta name="viewport"> tag, a default layout width is used (e.g. Chrome uses 980px). When the browser loads the page it does so maximally zoomed out. It looks like your device size above has a width of 425px so the browser zooms out when the page is loaded to see the whole 980px. If you have content that's wider than this (e.g. your image) it'll zoom out even further. Seeing as how your window.innerWidth is 1248, that implies a scale factor of about 30%.
tl;dr: innerWidth/innerHeight reflect viewport with the pinch-zoom factor applied and the page is loaded fully zoomed out.
EDIT: This has since changed in Chrome. window.innerWidth now returns the layout viewport width. To get the visual viewport width, use window.visualViewport.width. See this article for more details.
I'm not sure if this is a recent update (since the last responses), but I was able to find the viewport height/width by using:
window.screen.width
and
window.screen.height
This was particularly useful when I was trying to test whether the screen was phone-sized or not.
We're currently having success with something like:
const widths = [window.innerWidth];
if (window.screen?.width) {
widths.push(window.screen?.width);
}
const width = Math.min(...widths);
The conditional check is there because I'm not sure how widespread the screen width API is. You may need to adjust this not to use certain newer JS features depending on what devices you are targeting/your build process.
This could potentially go a bit weird if you have a window that is wider than the screen, but for us that isn't a problem.
This gives us a width that matches the one at the top of the Responsive screen tool, even when contents overflow horizontally. This is important for us because we needed the UI to change in order to prevent that overflow, but the overflow was interfering with the width number we used to trigger the adjustment.
I'm not sure if this is important, but we are also using:
<meta name="viewport" content="width=device-width, initial-scale=1" />

window.innerWidth in JS doesn't equal to `width:100%` in css

I am creating a webpage on mobile, which will fit 100% width of the screen.
However, when I created some elements with JavaScript and set the width to window.innerWidth, they would be much wider than the static elements that set width: 100% in CSS. (on iPhone 6(s))
The width: 100% sets these elements to 375px, which I think is right, since the screen resolution is 1334 x 750. However the window.innerWidth is 488px, for whatever reason I really don't understand.
Is this a bug of the browser I am testing, or I miss something for retina screen?
By the way, I use width:480px;max-width:100% to set the static elements. The view-port meta is like <meta name="viewport" content="width=device-width, initial-scale=1.0">
Pixel ratio and sidebars can cause the innerwidth of window to be different depending on the device. If you need to check window width in javascript so your media queries match up. Use the window.matchmedia function.
JS
if ( window.matchMedia('max-width:800').matches ){
console.log('tablet mode');
}

How do I get the browser window's width, regardless of the body's scrollbar?

The common ways to get the browser's width are all dependent on whether or not <body> has a scrollbar. For example, window.innerWidth, document.documentElement.clientWidth, $(window).width(), $(window).outerWidth(), etc all return different results for the following 2 cases:
<html>
<body>
<p>No scrollbar.</p>
</body>
</html>
and
<html>
<body>
<p style="height:10000px">Yes scrollbar.</p>
</body>
</html>
$(window).width(), etc, all return a higher value for the first case because the scrollbar's width is subtracted for the second case.
How can I reliably get the browser window's actual width regardless of the scrollbar's existence?
Edit: The suggested possible duplicate's answer says to use $(window).width() while I specifically said $(window).width() doesn't work.
Please try this
I dont know whether this method is correct or no. But you will get actual width 677 of the sample window
$(document).ready(function(){
$("body").css("overflow", "hidden");
alert($(window).width());
$("body").css("overflow", "auto");
});
DEMO
You will get the width of the window with the scroll bar as 677 when there is no overflow. Demo for screen width without scroll bar
You will get the width of the window with the scroll bar as 660 when there is overflow. Demo for scree width with scroll bar.
Here is a nice run down of viewport properties from the Quirks Mode site.
The window.innerWidth is the simplest way of getting this (supported in IE9+ and all other browsers)
// Get the size of the viewport including scrollbars:
var width = window.innerWidth;
console.log('innerWidth=', width);
And here is the MDN documentation on the innerWidth property.

Ad image in full screen for mobile devices without scrollbar

I would like to create an HTML/CSS/Javascript page that can show a picture (an ads) in full screen for mobiles. Smartphones + tablets. The ads stretch to the maximum width and height and there is no scrollbar.
I try two diferent ways :
var screenWidth = $(window).width();
var screenHeight = $(window).height();
$('body, .ads-picture').css('width', screenWidth+'px');
$('body, .ads-picture').css('height', screenHeight+'px');
And in other way with media queries for each devices.
But it doesn't work in any situation. In iPhone 5 the picture is not in full screen (I need to scroll), in iPad mini also.
Can you help me please ? Thanks !!!
add the following tag and put width: 100% im the images
<meta name="viewport" content="width=device-width, user-scalable=no">
get more info about it here

Can't reliably detect scroll bottom between iPhone portrait and landscape modes

I'm trying to detect when a user has scrolled to the bottom of the document. My current solution works fine in desktop browsers, and with Mobile Safari in landscape mode (with a 1px variance that I can't yet explain). However, I'm getting a completely different result for Mobile Safari in landscape mode.
I have a working example here: http://dl.dropbox.com/u/5634676/checkbottom.html
The detection routine boils down to:
if ($(window).scrollTop() + $(window).height() >= $(document).height())) {
// Bottom reached
}
Can you explain the difference between the two modes and help me reliably detect when the user has scrolled to the bottom of the document?
Update
I've updated the linked example fixing the bug pointed out by theflyingbrush. The results for landscape and portrait modes are now closer together (but there is still an as yet unexplained variance of 52px). Importantly though, for both portrait and landscape modes scrolling to the bottom of the page is still not detected.
I had the same issue on IOS mobile devices. Replace 'document' with 'body' fixed my issue.
if($(window).scrollTop() + $(window).height() > $('body').height() - 200 )
Also, it is better to check if 'near' bottom of the screen.
The height of the window changes when the device orientation changes, invalidating your windowHeight var stored on doc ready. Update it by listening for the orientationchange event and recalculating the window height. Something like:
window.addEventListener("orientationchange", change);
function change(){
windowHeight = $(window).height();
}
Edit: Confusing this, because it also involves the viewport scale. Here's a link to a working version: http://appunit.co.uk/scroll
You need to account for the height of the address bar in your calculations, because $(window).scrollTop() returns 0 until the address bar is scrolled offscreen. So, add the address bar height (60px) to scrollTop to get the distance scrolled. This is made more complicated if you haven't set a viewport meta tag in your html specifying width=device-width. In that case the viewport will be scaled from 320x356 to 980x1091, and the amount of virtual height the address bar takes up is scaled also. Summary:
var scaleFactor = ($(window).height()/356).toPrecision(2);
// toPrecision(2) prevents rounding error..
var addressBarHeight = 60 * scaleFactor;
// and when calculating scrollTop
var scrollTop = addressBarHeight + $(window).scrollTop();

Categories

Resources