JavaScript test if a CSS stylesheet is applied with CSS3 media query - javascript

I have two style sheets:
<link rel="stylesheet" type="text/css" href="/core.css" media="screen" />
<link rel="stylesheet" type="text/css" href="/core-desktop.css" media="only screen and (min-width: 800px)" id="css-desktop" />
The second one should only be loaded when the window is 800px or wider (narrower displays get a layout more appropriate for mobile devices).
The JavaScript needs to know if that second style sheet is being applied, I have tried the jQuery:
($(window).width() > 800)
But when you get around the 790 - 810px width, Chrome/Firefox (and probably others) will return a value such as 791, and the 800px+ style sheet will still be loaded.
I suspect it's due to the scroll bar (but targeting the $(document) or $('html') either doesn't work, or are the same).
So is there a way to test if $('#css-desktop') is enabled/active/used?

You can do the following.
Make a div which has a display: none; in the first stylesheet, so it is not shown.
In the second stylesheet you will add a position: absolute
In your Javascript you check if( $("#thediv").css("position") == "absolute")
The position: absolute; is only applied in the second stylesheet.

You could try
window.matchMedia(document.getElementById('css-desktop').getAttribute('media')).matches;
https://developer.mozilla.org/en-US/docs/Web/API/Window/matchMedia

Here is an example as to how you can try to detect the "real" width of the browser window: detect window width and compensate for scrollbars - Javascript

There is a problem with what you are attempting.
If a user is browsing the page while resizing the window below 800px in width then, he will get the mobile version of the page and later when he/she maximizes, he will still get the mobile version.
So, relying on screen width are not a reliable method as the screen resolution of the mobiles are growing significantly nowadays.
Your best shot is to read the User Agent information of the browser, which will easily reveal whether it is a mobile browser or other and load the css files according to it. Then for the variable screen resolution, you can use your current techniques to load width specific codes.

Related

Responsive webpage without meta tag?

I'm guessing the answer is no but is there a reliable way to make a webpage responsive without adding a viewport meta tag to the head?
I have added a login form container that's 400px wide and centered vertically and horizontally. It looks fine on desktops but it is zoomed way out and looks tiny when you access the page on a mobile phone. Users have to swipe multiple times to zoom in so they can use the login form.
I don't have access to the head. I can only create a container within the body. However, I can add CSS for anything and basic JavaScript. I have limited access because the webpage is generated by a server program. It only allows adding a CSS file and header & footer HTML files. Basically, it limits me to wrapping the form and error container with a custom container.
You can build a responsive websites using CSS's #media rule.
Media queries allow you to apply specific css style's depending on device type an characteristics. Consider the following code, for example:
body {
background-color: yellow;
}
#media only screen and (max-width: 600px) {
body {
background-color: blue;
}
}
This code will result in your page's background color being blue until the screen width is <= 600px.
Read this MDN article for a more detailed explanation on media queries.
You can use JavaScript to program your own responsive behaviors. A simple example would be to scale the html container by the devices pixel density.
"window.devicePixelRatio" gives you the actually number pixels per css pixel. Then scale your container by it:
const pixelDensity = window.devicePixelRatio;
document.getElementById("container").style.transform = "scale("+pixelDensity+")";
Css media queries may not work properly, but again you can use javascript to dynamically load styles based on the adjusted screen size when multiplying by the pixelDensity above.
From a quick glance (at Can I change the viewport meta tag in mobile safari on the fly? for example) it seems you can really create and inject relevant meta tag with JavaScript, like:
<script>
(function(){
var m = document.createElement('meta');
m.setAttribute('name','viewport');
m.setAttribute('content','width=device-width, height=device-height, initial-scale=1.0, minimum-scale=1.0');
document.head.appendChild(m);
})()
</script>
Test page: you should see wide overflowing dark paragraph before tapping the button which executes above function. After that the paragraph should fit into the viewport.
You can do it with JavaScript, but it can be apply only after the page was loaded, so it's not usefull in your case...

$(window).width() not giving viewport width correctly

I have almost always used $(window).width() to check the viewport width. It normally works for both browsers and devices. But for a website on which I need to show a particular splash screen if viewport width is less than 768px, this is not working. It gives correct width upto a point but below that it keeps giving 980px howsoever narrow I make the browser. There are a few particular conditions for this site:
This site was responsive in beginning (using bootstrap) but then made non-responsive. For this we removed viewport meta tag and set following rule in css that overrides its responsive widths:
.container{ width: 1170px; }
If I resize the whole browser i.e. the window that contains all browser tabs, then it does give correct width (less than 980px also, which is the desired behaviour), but if I use development tools and use the mobile layouts from there then width is never reported to be below 980px.
It would not have mattered that it worked on resizing only the main browser window, but the issue is that it is not working in devices as well. I added an alert and on mobile devices, again width is never alerted to be less than 980px.
Can someone please suggest some solution for this or explain why it is not working as expected?
I can't seem to find any authoritative source, but there are many pages that mention smartphones assume a website is 980px wide unless told otherwise.
Apple's developer site for instance says
The majority of webpages fit nicely in the visible area with the viewport width set to 980 pixels in portrait orientation, as shown in Figure 3-4. If Safari on iOS did not set the viewport width to 980 pixels, then only the upper-left corner of the webpage, shown in gray, would be displayed. However, this default doesn’t work for all webpages, so you’ll want to use the viewport meta tag if your webpage is different. See Supported Meta Tags for more on viewport.
Figure 3-4 Comparison of 320 and 980 viewport widths
(Incidentally, it was the iPhone which first did this, but other phones soon followed.)
So the solution is either to put
<meta name="viewport" content="width=device-width">
into the head (in your case, back into the head), or, acknowledge that the site is now not-responsive, and will not perform optimally on a phone!

CSS, change stylesheet if mobile device

I'am having trouble changing CSS file paths if the end user is accessing my site via a PC or mobile device, below is my CSS, I thought that it would redirect the user if using any handheld device:
<link rel="stylesheet" type="text/css" href="/css/style.css" />
<link rel="stylesheet" type="text/css" href="/css/mobile.css" media="handheld" />
Please can someone let me know if this is the correct way or should I be using javascript to manipulate my file path>
Dont make life too hard on yourself going that route of detecting a browser and device type..
Go with Media Queries..
#media only screen and (max-device-width: 480px)
All devices are now all well known but regardless the resolution will determine the css style you offer the client..
A Lot more can be found here : MediaQueries
I would suggest MAYBE bootstrap3 framework // foundation etc there are a lot to choose from but these are the top two which come with built in definitions and a good framework to write css for each!
What you want to focus on is the grid system..
such as Bootstrap They work of a col-size-n grid of 12 colums, responsive.
A Lot more documentation can be found there and it opens a world of other questions!
:)
Well, the proper way would be Media Queries.
As mentioned by another individual on your question, if your truly trying to utilize Javascript:
function Resize() {
width = window.innerWidth;
height = window.innerHeight;
if(width < 1200 && height < 600) {
// Modify particular Stylesheet elements.
}
}
Obviously you can do measurement / comparison:
Browser Inner Width / Height
User Agent
Those are two examples, but really Media Queries would be ideal and proper. Won't go into detail on those Media Queries, since someone went into more detail.

How to show initial-scale 1.0 to devices below 570px width only

On my website, I have a mobile version for devices below 980px, however I would like devices blow 570px only to see this and if they rotate their mobile device, for them to then be able to see the full site with their device scaling if needed.
Change my pages width to see the mobile version. This is what I want devices to see on portrait mode but in landscape I would like them to see full version. I thought about implementing tilt detection, however nowadays you can get 27" all-in-one touch computers which can tilt!
If you don't have the viewport tag included, then the page will render using the device resolution. That means it will likely return 980px not the css pixels you're expecting. This is the default value of most mobile browsers (on Android and iOS devices at least). So, trying to add the viewport tag by checking if the width of the window is less than 570px without already having the viewport content tag set to "width=device-width" would be fruitless. This is why your first attempt did not work.
Also, if you try and remove the viewport tag AFTER the page is already rendered (for instance, inside a $(document).ready(function () {}); it would remove the tag, but the page would be unaffected.
However, you can set the viewport tag to have a different content value. So, in this case, you'd include the <meta name="viewport" content="width=device-width, initial-scale=1.0"> on the page, then in your document ready, use jQuery to set the content attribute to default width value of 980px instead. Because the DOM is ready when you are checking the width of the window, changing the value of the content attribute will cause devices that honor this property to render the page at the default 980px. (This is horribly small on my iPhone5 and impossible to use, but you stated that you find it acceptable.)
//add this to your document ready function and make sure
//that the viewport is initially set to content="width=device-width"
var pageWidth = $(window).width();
if (pageWidth < 570) {
$('meta[name="viewport"]').prop('content', 'width=980px');
}
Why you don't have to worry about resize events:
For most current devices that you are targeting, the window width is not resizable and the resize event will not be triggered on orientation change because it's not a change in the width of the browser, rather it's a change in zoom level. On your desktop, however, the browser won't even care about the viewport meta tag at all, so, no matter what value you have there, it doesn't affect the behavior.

mobile version of website doesn't fit horizontally

I'm trying to produce a mobile version of my website, but have encountered one problem:
The the whole website fits properly on the computer (with an example browser width of 480px) but leaves space on the right when viewing on my mobile phone (regardless of the browser I used). So the whole site looks good, but you can scroll "out of the website".
I first tried to disable horizontally scrolling, so I included this line:
<meta name="viewport" content="width=device-width; initial-scale = 1.0; maximum-scale=1.0; user-scalable=no" />
To disable the (still scrollable!) space on the right I added this to my "mobile.css":
It worked on the computer, but not on my mobile.
body{
width: 100%;
overflow-x: hidden;
}
My website is avaiable here: my mobile website
My mobile.css file is located here: my "mobile.css"
I have tested the website on following mobile browsers:
Google Chrome
Dolphin
The default android browser
I originally wanted to avoid Javascript, but if there is a javascript solution, please don't hesitate to post it!
If you want your layout to be mobile friendly, it's best to be thinking about this right from the beginning. So, for example, if you are going to set fixed widths on elements (which I don't recommend), such as—
#back-menu-left {with: 500px;}
you need to ask yourself what will happen to this on a small screen. So, either don't set that width, or immediately write an #media rule to override it on smaller screens.
(I didn't check through the rest of your code, just stopping when I found one oversized element. Best to check and see if there are any other overwide elements like that.)

Categories

Resources