How to detect screen size for responsive web design? - javascript

I googled this and got a quirksmode site that gives you your screen size. Pulling up the console I see that screen.width and screen.height are directly available from the window object.
I want to do the detection in pure JavaScript to get started. Can I use this property across all devices and browsers - mobile, tablet, PC and Chrome, Safari, IE, Firefox.
I don't care about the view port changing due to re-sizing etc. Just the actual size of the screen which does not change.
I was hoping there was a single property I could check across devices and browsers.
Here is some general info by wikipedia on responsive web design.

Take a look at Get the device width in javascript
Media Queries work in js too:
if (window.matchMedia('screen and (max-width: 768px)').matches) {}
Another way would be:
var width = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);

screen.width is the property your are looking for.

This is what worked for me after long hunch.
These attributes below provide responsive sizes based on new tab size.
window.innerWidth
window.innerHeight

Related

Javscript - How can I determine physical screen width and height

What I want
I want to know physical screen width and height using javscript
Why I want
I want it so that I can use it when a portrait screen device(like mobile phone) wants to have a video call with landscape device(like laptop). This way I can swap width and height constraints according to the other end of the call. So for mobile device I will send video in portrait mode and for laptop I will send it in landscape mode, by swapping width and height dimensions(constraints).
I would like to know a device original screen size or orientation irrespective of browser widow size change or device is orientation change.
I have already found many posts asking about orientation or dimensions but they all seem to have some flaws, according to the comments, and some don't address physical screen dimensions.
I have mentioned what I aim to achieve. Maybe there is a better way to achieve that.
Please help.
Thank you
You could use screen.height and screen.width properties in javascript to get the height and width of the user's screen in pixels (irrespective of the browser size).
> screen.width
2048
> screen.height
1280
This works with most browsers and certainly works with Chrome, IE, Safari, Firefox, Opera.
Use
window.height and window.width

Get Height of Surface Pro 3 on web page

I have a monitor with 1920x1080 resolution for my laptop and a Surface Pro 3 with 1920x1280 resolution. I am developing a web page designed for full-screen viewing on 1920x1080 and 1920x1280 displays.
I have confirmed the settings for each display (see below).
Why am I getting 8xx instead of 1280? How can I obtain a value of 1280 to match the resolution height of the Surface Pro 3?
1920x1080 monitor (on Windows 8):
1920x1280 (Surface Pro 3) display (on Windows 10):
Using $(window).height() on my 1920x1080 monitor, I get the following:
That works for me.
However, using suggestions from this question for my 1920x1280 (Surface Pro 3) display...
Using suggestions from the accepted answer.
Using $(window).height():
Using $(document).height():
Using screen.height:
Using the suggestion from this answer:
Using the suggestion from this answer:
Using the suggestion from this answer:
Using the suggestion from this answer and this answer and this answer:
Using this suggestion from this answer:
This suggestion is a self-recommendation of a plugin. I will pass on this for now.
This suggestion uses a Coffee solution. I'll stick to JavaScript and jQuery for now.
Using this suggestion from this answer (which regurgitates a few other answers):
This suggestion requires an external library. I will pass on this for now.
Using the suggestion from this answer:
This suggestion was incorporated into a few other answers above.
It seems that your Surface Pro 3 uses an operating system wide zoom factor of 150%. Due to this the browser returns width 1280 and height 853 (as 1280 * 1.5 = 1920 and 853 * 1.5 = 1280). Switch Windows' zoom factor to 100% in Control Panel and your browser will return width and height as expected.
1) How can I obtain a value of 1280 to match the resolution height of the Surface Pro 3?
Have you tried
window.outerHeight
yet?
All I see in your test cases is the innerHeight.
That's only showing you what the browser will render(pixels will be zoomed, etc.. decreasing the available width you actually have)
2) Why am i getting 8xx instead of 1280?
Basically, browsers will zoom text/images/ etc.. to give a consistent experience across several resolutions.
Even though you are building it for a 1280 screen, you might only have 8xx pixels to your availability.
For more information about the pixeling I advice you read:
http://www.quirksmode.org/blog/archives/2010/04/a_pixel_is_not.html
Here is a solution that worked for me in Firefox, Chrome, IE11, and Edge. I don't have a Mac to test on but this should work there too. You need to factor in the device pixel ratio. Here is an example (JSBin):
var screenHeight = window.devicePixelRatio * screen.height;
This will give you the screen dimensions regardless of DPI of the device.
An important thing to note is that innerHeight (size of window without browser UI) and outerHeight (size of window with browser UI) are relative to the browser window. You should use those instead of screen.height if you want to know the size of the browser window.
In the browser, you deal with the abstraction of CSS pixels, not with physical pixels. The size reported to you is most likely correct (unless there is a weird browser bug at play), so the height of the window is 853 CSS pixels.
My advice would be to work with that size. Adjust your layout with media queries etc. Don't try to second-guess the browser; don't optimize for hardware specifics which browser vendors, and web standards, are actively trying to hide from you.
(I'll try to expand this answer later on, if I have the time. A proper explanation of the concepts is the length of a blog post.)

javascript vs media queries

I'm looking at creating a responsive framework for my website - its a first for me. No fancy stuff just responsive through mobile -> tablet -> desktop.
I'm happy with how media queries work, however adding classes through javascript seems like another viable option.
It would be easy to do something like this:
function queryViewport() {
var $window = $(window);
var $body = $("body");
var windowWidth = $window.width();
var windowHeight = $window.height();
// Query window sizes to determine whether device is to be
// classified as a small mobile device or a larger tablet/
// desktop device.
var isMobile = windowWidth < 600 || windowHeight < 600;
$body.toggleClass("mobile", isMobile).toggleClass("desktop", !isMobile);
// Calculate whether viewport is portrait or landscape
var isPortrait = windowHeight > windowWidth;
$body.toggleClass("portrait", isPortrait).toggleClass("landscape", !isPortrait);
}
However, I'm not an expert in this area - am I missing something or is it really that simple?
All advice appreciated.
you can use this minified jQuery snippet to detect if your user is
viewing using a mobile device. If you need to test for a specific
device I’ve included a collection of JavaScript snippets below which
can be used to detect various mobile handheld devices such as iPad,
iPhone, iPod, iDevice, Andriod, Blackberry, WebOs and Windows Phone.
if(jQuery.browser.mobile)
{
console.log("You are using a mobile device!");
}
else
{
console.log("You are not using a mobile device!");
}
See more DETECT MOBILE DEVICES USING JQUERY
See the link below to understand the difference
What is better: CSS media queries or JQuery mobile?
I would suggest media queries, as all future amends can be done in the CSS without adding more and more logic to a separate JS file for new breakpoints.
Additionally, the CSS solution is supported down to IE9+ and there are JS polyfills (Respond) for backwards compatibility. Basically it's just built in to CSS and works well. There seems little point of rewriting the same logic in javascript, having a new class for every new size.
On top of this, media queries allow you to target CSS as different media types such as print, or if you want to use height-based media queries or target retina displays you can do this without having to add new classes. As a rule the convention is to use media queries with JS fallbacks and I see no reason to suggest otherwise.
JS produces different results for detecting viewport heights and widths depending on how you get them:
In that case, you could get screen width using window.outerWidth, window.innerWidth, document.documentElement.clientWidth. All these produce different results, but the second will give you values identical to CSS #media breakpoint.
$(window).width() too, is different from #media breakpoint.
I depends on browser differences, e.g. if the take in account the vertical scrollbar or not. Better go with CSS.

Newest method to detect small screen

While waiting for responsive design to find the way into a legacy web site, I would like to redirect a browser to a mobile version if the screen is smaller than 480px
Hunting around I came up with
var isSmall = window.matchMedia ?
window.matchMedia("screen and (max-width: 480px)") :
screen.width<=480;
Question
Is this acceptable in 2014 or is there a better/safer/newer method to do what I want without using useragent sniffing?
References
MDN Window.matchMedia
JavaScriptKit CSS media query matching in JavaScript using window.matchMedia()
QuirksMode screen.width is useless (hence the addition of matchMedia)
You could use a polyfill such as https://github.com/paulirish/matchMedia.js/
you can use bootstrap http://getbootstrap.com/ or
foundation http://foundation.zurb.com/
these two frameworks has a powerful multi device layouts.
Yes there is lot of tricky ways :) to choose windows width but our Team's view you didn't have to include any tricks to know just windows.width because jQuery has a .width() function like:
var window_width = $(window).width();
if( window_width <= 480 ){
console.log(window_width);
}
Iphone 4S, Iphone 5, Iphone 5S Every one's Screen Width is 320px. Your Mobile Resolution isn't your mobile's Screen Width. so when you include your tricks to know just windows width or something you just increase your Application's loadspeed this gonna be a problem for your user. But you know that was the designer's issue why they complicate the designs for developers & for End Users. :)

Responsive CSS with high-res smart phones and tablets

I am having a issue when I try to make a web app responsive to screen-size.
I have css that I want to use for smartphones (iPhone, Andriod, blackberry, windows phone), and also have CSS I want to use for tablets.
My test devices are an iPad 3 (768 x 1024) and blackberry 10 (768 x 1280). and the widths being the same is an issue because my css starts with:
#media screen and (max-width:768px){
//enter code here`code here
}
Because the blackberry has slightly better resolution, it renders the CSS I don't want to use for it. Is there another way I'm suppose to check the media type? I was wondering if there is a way to check the width with a measurable distance (cm or in). not sure how to solve this.
thanks in advance
The “pixels” that are used in CSS declarations and when the browser reports the screen size of the client device have nothing to do with the actual real-world pixels on a device's screen. The “pixels” that are used in CSS are essentially an abstract construct created specifically for us web developers. To concern your self with the actual amount of real-world pixels on a high-resolution mobile screen is, for most web applications, completely unnecessary and will only lead you to utter madness.
You can determine the browser and device type by inspecting the navigator.userAgent property in JavaScript. For example, to test for (practically) any mobile device:
// if mobile === true, 99% chance the device is mobile.
var mobile = (/iphone|ipad|ipod|android|blackberry|mini|windows\sce|palm/i.test(navigator.userAgent.toLowerCase()));
You can of course inspect navigator.userAgent to determine if the user is on a specific type of device or browser that you are particularly concerned about or having a problem with.
But again, in my personal experience, clever, simple, and flexible responsive CSS design (supported by media queries and JavaScript, too, of course) will render beautifully on 99% of device/browser combinations without having to resort to inspecting navigator.userAgent to create different styles for individual devices.
You can also restrict your styles to the height:
#media screen and (max-width:768px) and (max-height:1024px){
// iPAD
}
You should add the meta tag viewport in your html header :
<meta name="viewport" content="width=device-width, initial-scale=1">
To sum up :
width = device width x pixel density
(Galaxy S4 : 1080 = 360 x 3)
This metatag allow you to catch the device width instead of the "faked width" (360 instead of 1080)
Some good reading :
https://developer.mozilla.org/en-US/docs/Mozilla/Mobile/Viewport_meta_tag
http://screensiz.es/phone
http://www.html5rocks.com/en/mobile/mobifying/#toc-meta

Categories

Resources