How to detect mobile browser for screen size? - javascript

I'm working on a site that needs to work on desktop and mobile. Right now I have a main content div that is set to 70% of the screen width. However, I feel that this is to small for mobile devices (like phones, not so much tablets) and want to up it to 90 or 95% How can I do this (say for screen sizes smaller than 5 inches) without using terribly unreliable browser sniffing? I hear the mantra "feature detection feature detection feature detection" over and over, and I understand why that's a good thing...but I don't know what "feature" to detect for this problem...
Thanks.

You can use CSS:
#media screen and (max-width:500px) {
/* smaller screens */
}
#media screen and (max-width:960px) {
/* bigger screens */
}

You can get a wild approximation of the screen size with a bit of javascript
function getScreenSizeInches() {
var temp = document.createElement("div")
temp.style.overflow='hidden';
temp.style.visibility='hidden';
document.body.appendChild(temp)
temp.style.width = "10in"
var dpi = temp.offsetWidth / 10;
return screen.width / dpi + 'x' + screen.height / dpi;
}
See the following fiddles for its use in action vanillajs, or jquery..
jQuery version:
function getScreenSizeInches() {
var $temp = $('<div style="overflow:hidden;visibility:hidden;width:10in"/>').appendTo('body'),
dpi = $temp[0].offsetWidth / 10;
return screen.width / dpi + 'x' + screen.height / dpi;
}
As has been pointed out in the comments this technique can be wildly inaccurate so I wouldn't use it as anything other than a hint toward screen size...

You could use CSS:
/*Here goes the CSS for all screens*/
#media handheld {
/*Here goes the CSS for mobile phones and tablets*/
}
EDIT:
Another suggestion:
set the viewport metatag in your html:
<meta name="viewport" content="width=device-width, height=device-height" />
now you can get the dimensions like this: Get the browser viewport dimensions with JavaScript

Instead of using jquery you can use simple javascript to detect it:
if( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
}
or you can combine them both to make it more accessible through jQuery...
$.browser.device = (/android|webos|iphone|ipad|ipod|blackberry/i.test(navigator.userAgent.toLowerCase()));
now $.browser will return "device" for all above devices

these days you can probably use the Screen API. screen.height or screen.width
https://www.w3schools.com/jsref/obj_screen.asp
https://caniuse.com/#feat=mdn-api_screen

to get physical size you could not use Javascript but use jQuery to get screen size
$(document).ready(function(){
var elem = document.createElement("div");
$(elem).attr("id", "removeMe").css({"width":"100%", "height":"100%", "position":"absolute", "top":"0", "left":"0"});
$("body")[0].append(elem);
width = $("body #removeMe").width();
height = $("body #removeMe").height();
$("body #removeMe").remove();
});
This will get you the Pixel size of the screen. however i would combine this with a mobile check like #Abhi jQuery answer and you would need to drop this code into a window resize event handler so if the mobile screen rotation is on and is turned you have the new mesurements

Related

window.screen.width value not changing in iPad browsers when screen orientation changed

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
}

how to set a minimum width for your site / viewport and have browser scale if the width is below that

I'm trying to wrap my brain around viewports / scales. I have a site I have to program, and the design I've been given is responsive, but it really doesn't work if the device's width is below 420px.
At anything below 420px, I'd love it if the browser would render the site as if it were 420px wide, just zoom everything out, but I can't figure out how to do this.
I've seen how you can dynamically change the meta viewport tag, but when I do this, it doesn't seem to have any affect, and I'm not sure that's the best way to approach what I'm trying to achieve.
At any rate, this is what I tried:
var minBP = 420;
//ww = window width
if (self.ww < minBP && lastScreenWidth > minBP){ //site is smaller than minimum allowed width, modify viewport
var viewportString = "width=" + minBP + ", initial-scale=1.0";
$('#blackrock-viewport').attr('content',viewportString);
}
Anyone know how to render a scaled-out 420 viewport width when the browser drops below these dimensions?
well you can do that in css by using Media Queries it allows you to manipulate evrything in diffrent screens
for exemple if you want to change the width of div in 420px screen you can do this :
#media (min-width:420px) {
div{
width:50px;
}
}
You can just use media queries to target specific elements on specific screen sizes.
For your situation, you just have to limit your wrappers width to your preferred size.
Supposing that you have a div that wraps all your page, let's say .wrapper.
#media screen and (max-width:420px) {
.wrapper{
width:420px;
}
}
Of course, you can do this also without media queries by just setting the min-width property of your wrapper.
.wrapper{
min-width:420px;
}
But I suppose that with media queries you are more flexible.

Using returned viewport queries as SASS variables

I just don't see anyone talking about this exact issue out there. Looking to have site fit any screen exactly with no scroll. Certain elements being fixed ratio (logo, video players, etc) means other areas have to expand/contract amorphically to accomodate their fixed behavior that can't ever go past 100% width or height. Difficult to explain, but the behavior in sassmeister gist below shows it working. To do this, I need to be able to define widths in terms of heights, and vice-versa (width = 56.25% of height, etc)
I can make it work using vh, vw, vmin, a bunch of calc functions etc... but browser support is patchy, and I'm unaware of a polyfill to smooth all that out. My vh, vw, calc solution below:
http://sassmeister.com/gist/3dee56a4092a86cf070a
Only other pure css I'm aware of that even begins to address this is the percent padding trick tying padded height to parent width, but this alone isn't enough. I need to be able to use min, max statements, and tie width and height going both ways.
So... unless I'm mistaken, #media queries only ever return true/false, so they can't provide an actual viewport measurement to use, right? That's what I really need... a pixel accurate measurement of the available viewport height and width.
What's the solution here? Should I use javascript to get those exact dimensions, then do all the arranging in javascript? Use JS to get the variables, then pass them on to the css?
Something like this: https://gist.github.com/scottjehl/2051999 and a method to import those returned values into css should work, no? Is that slowing the site down too much to have the js call first before anything else happens?
Also, need to find the right way to do all these calculations. Should I just be using javascript to do all the calcs and leaving stuff like the following out of css completely?
$gutter: calc(((100vh + 100vw) / 2) * 0.04)
Then using that variable inside another function:
$column-width: calc(100vw - (1.7778 * (100vh - 2 * $gutter)) - 3 * $gutter)
You get the idea. I think I'm nearing the end of what I can do with the css. JS solution? Hybrid? Something else?
thx.
It sounds like media queries are what you're looking for.
You can use the following to target screens with a max width of 1200 px and a min width of 800:
#media all and (max-width: 1200px) and (min-width: 800px) {
//some css here
}
Check out the way bootstrap-sass implements containers here.
Also check out the other SO answer about media queries.
You can even specify landscape and portrait layouts.
#media (orientation:portrait) { ... }
Or aspect ratio:
#media screen and (device-aspect-ratio: 16/9) { ... }
I hope this helps. You can use some of those fancy gutter calculations inside of/with media queries and that should simplify things a bit.
This javascript will return the screen height:
var x = "Total Height: " + screen.height;
document.getElementById("demo").innerHTML=x;
Width:
var x = "Total Width: " + screen.width;
document.getElementById("demo").innerHTML=x;
Some JQuery:
$(window).height(); // returns height of browser viewport
$(document).height(); // returns height of HTML document
$(window).width(); // returns width of browser viewport
$(document).width(); // returns width of HTML document

How to identify screen size

I am working on some mobile web application (it my firs time) and I faced such problem: despite the use of special mobile frameworks some sizes of modal windows are not correct on small screens. For example i have an ipod and ipad:
On iPod the size of buttons is already changed for a bit. So, may be there is any way to identify screen size like category (small, normal, large or may be just get list of sizes to the array) using js may be and then based on it i would do some basic changes in the source.
use jquery to find current width of window
$(function() {
showWidth($(this).width());
$(window).resize(function() {
showWidth($(this).width());
});
});
function showWidth(wid) {
var width = parseInt(wid);
if (width < 1440) {
//use wider stylesheet
} else if ((width >= 901) && (width < 1440)) {
//use wide stylesheet
} else {
//use small stylesheet
}
}
You can get screen height width using jquery like
alert("Width :"+$(window).width()+" Height :"+$(window).height());
You does not get size specification like small,big etc.
You have write responsive code yourself using screen width and height.
I would strongly suggest to use css media-queries instead of identifying the width in js and serving stylesheets based on that.
CSS Media Queries are standradrized: http://www.w3.org/TR/css3-mediaqueries/
Also see examples and usage here: http://css-tricks.com/css-media-queries/

Listen for browser width for responsive web design?

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.

Categories

Resources