How to identify screen size - javascript

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/

Related

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.

How to ignore javascript on smaller resolutions?

My dev site uses lots of Skrollr animation at 1024px resolutions and up. Under 1024px, I don't want the animation to show, so I hid all of the images and whatnot.
However, the javascript that gets called to make the animation work is still getting called on smaller resolutions and causing some issues.
Is there a way to basically say "If the resolution is less than 1024px, ignore these JS files"?
I tried putting them in a DIV and using my existing CSS media queries to "display: none" the DIV on smaller resolutions, but that doesn't work.
FYI, these are the files being called:
<script type="text/javascript" src="/js/skrollr.min.js"></script>
<script type="text/javascript" src="/js/homepageanimation.js"></script>
On top of the jQuery(function($) { in http://workwave.joomlatest01.mms-dev.com//js/homepageanimation.js put something like
jQuery(function($) {
if(screen.width < 1024) {
return;
}
// skrollr stuff....
}
so all the skrollr functions won't be called on screen sizes with a width below 1024px.
The easiest way is too use jQuery..
$(window).width();
plain Javascript:
var w = window.innerWidth;
var ow = window.outerWidth; //toolbars and status, etc...
if(w > 1024) {
//Skrollr
}
from there an small if to trigger the Skrollr event
I would suggest conditionally loading the script. Basically the script only gets loaded if the screen size is greater than 1024.
if(window.innerWidth >= 1024){
var file = document.createElement('script')
file.setAttribute("type","text/javascript")
file.setAttribute("src", "/js/skrollr.min.js")
}
A nice approach here would be to only call the function that initiates the Skrollr functionality at given screen sizes. A real quick Google suggests that Skrollr has a .init() function that gets things rolling.
Without seeing how the JS is set up it's hard to give any solid advice, but here's an idea:
You have a JS file for the page/site that contains a conditional that checks the width of the window before initializing the plugin after the document is ready.
$(document).ready(function() {
if ($(window).width() > 1023) {
skrollr.init();
}
});
jQuery makes this a lot easier too, so it's worth taking advantage of that.
Another option to consider instead of going via window width (which can sometimes be inconsistent with the CSS widths among different browsers) is to test against a CSS rule and whether it is true, so use one you know would be true at a size above 1024px, and this would eliminate any inconsistency.
Within this condition link the JQuery files as demonstrated in other answers.

Dynamically change css fontSize with jQuery or css

I have a span that needs its font-size value changed when the window is resized. I do that with the jquery code:
$(window).on('resize', function () {
y = $(window).height();
x = $(window).width();
if (y > 500) {
$('#testing').css("fontSize", "50px");
} else if (y < 500) {
$('#testing').css("fontSize", "10px");
}
});
and may also do an equivalent with the css code:
#media screen and (max-height: 500px)
{
#testing{
font-size: 10px;
}
}
which is actually more efficent? Is one solution more acceptable/common? Is there a better way to do this? And also which way is more acceptable on a mobile device? Is there a better way to do this on a mobile device?
Which is actually more efficent? Is one solution more acceptable/common?
Performance wise, CSS is way better. Using media queries will be faster than processing a function on every resize (which are called numerous times). Of course, you could insert a throttle and call it once when the window didnt resize in a said lapse of time, but even there, media queries will be faster.
Furthermore, Javascript window width may not alway be the same than the CSS media queries. Scrollbar can change value and other things may also affect the width. You have to use a function to check the real width, which consume even more juice. It look like that :
function viewport() {
//Get the current view port
var e = window, a = 'inner';
if (!('innerWidth' in window )) {
a = 'client';
e = document.documentElement || document.body;
}
return { width : e[ a+'Width' ] , height : e[ a+'Height' ] };
}
The down side of mediaqueries is the support, it is not supported in old IE. But there is of course some libraries that solve this issue.
Is there a better way to do this?
Not really, media queries are fast and efficient.
And also which way is more acceptable on a mobile device? Is there a better way to do this on a mobile device?
Most mobile browser support media queries. You should always use media queries on mobile, it is the prime reason why they exist.
Self shaming promotion and why Javascript media queries could be usefull
There is a case where javascript could be used as media queries. It would be usefull if you want to change the font-size dynamically depend and a screen size with a ratio. Doing that with media queries would be long and painfull since you'd have to do 20~30 media queries depending on the smoothness.
I've created a plugin changing font size depending on the screen for that reason.
https://github.com/kagagnon/Responsive-Font
If you're not worry about cross browser compatibility problem since media queries is CSS3 which is not supported for old browsers such as IE7, IE8... then I'd suggest you to use CSS over javascript.
In the other hand, beside better in handling cross browser compatibility issues, if a task cannot be achieved through CSS then you should probably go with javascript instead.
In short, I'm always prefer CSS than Javascript :)
Depends, using a responsive design will allow you to do much more than just change the font size.
vw units is a good option if you can. See this article
As my opinion ,You have to prefer JQuery,because the reason is : It is a library that fully support most of devices and auto configure them self as per the environment need ! You have to not think about what the browser need only put a line of code jquery do it in its own way. And place apply your style with respect to device or browser !

How to detect mobile browser for screen size?

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

Syncing CSS and JS media queries cross-browser

When working on responsive designs I make use of CSS3 media queries, including with older browsers using respond.js. There are occasions when I also need to use JavaScript/jQuery for manipulating some elements on the page. However, when using $(window).width(), that value is often different than the value used in the CSS media query due to browser chrome and/or the presence of a vertical scrollbar, meaning a CSS media query will fire at a different breakpoint than the JS media query.
I know Modernizr alleviates this issue through the use of Modernizr.mq, but that only works in browsers that support CSS media queries to begin with, generally meaning it won't work in IE8 and below. And if you use a polyfill for adding media query support to these older browsers (e.g., respond.js), then the Modernizr.mq no longer works due to a conflict/override between the two.
What I've instead done is made use of a hidden input element on the page and given it a CSS width style within each of the media queries. I then have a function that runs automatically on the page (and on resize) that gets that width value and executes the following:
if (width == "320px" ) {
//Functions
}
//481px to 600px
else if (width == "481px" ) {
//Functions
}
//601px to 768px
else if (width == "601px" ) {
//Functions
}
//769px to 960px
else if (width == "769px" ) {
//Functions
}
//769 to 1024px
else if (width == "961px" ) {
//Functions
}
//1024px+
else {
//Functions
}
This basically forces the JS to work entirely off of the CSS media query, syncing the two. This can become more specific rather than generic as I have it, instead firing based off of a specific element and a specific style that changes on that element, it depends on individual project needs.
My question then is, is there a simpler way of doing this? I've spent considerable time looking into and experimenting with this and it seems the best option thus far that takes into account older browsers as well.
PPK listed a nice way to pair the CSS & JS on his blog which sort of backs up your method:
#media all and (max-width: 900px) {
// styles
}
if (document.documentElement.clientWidth < 900) {
// scripts
}
His full post on it is here.
There's also the enquire.js plug-in.

Categories

Resources