Setting the Viewport to Scale to Fit Both Width and Height - javascript

I'm working on a website that fits within a specific width and height (an 885x610 div with a 1px border and 3px top margin). I would like the user to never have to scroll or zoom in order to see the entire div; it should always be fully visible. Since devices have a wide variety of resolutions and aspect ratios, the idea that came to mind was to set the "viewport" meta tag dynamically with JavaScript. This way, the div will always be the same dimensions, different devices will have to be zoomed differently in order to fit the entire div in their viewport. I tried out my idea and got some strange results.
The following code works on the first page load (tested in Chrome 32.0.1700.99 on Android 4.4.0), but as I refresh, the zoom level changes around. Also, if I comment out the alert, it doesn't work even on the first page load.
Fiddle
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0">
<script type="text/javascript">
function getViewportWidth() {
if (window.innerWidth) {
return window.innerWidth;
}
else if (document.body && document.body.offsetWidth) {
return document.body.offsetWidth;
}
else {
return 0;
}
}
function getViewportHeight() {
if (window.innerHeight) {
return window.innerHeight;
}
else if (document.body && document.body.offsetHeight) {
return document.body.offsetHeight;
}
else {
return 0;
}
}
if (/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent)) {
var actual_width = getViewportWidth();
var actual_height = getViewportHeight();
var min_width = 887;
var min_height = 615;
var ratio = Math.min(actual_width / min_width, actual_height / min_height);
if (ratio < 1) {
document.querySelector('meta[name="viewport"]').setAttribute('content', 'initial-scale=' + ratio + ', maximum-scale=' + ratio + ', minimum-scale=' + ratio + ', user-scalable=yes, width=' + actual_width);
}
}
alert(document.querySelector('meta[name="viewport"]').getAttribute('content'));
</script>
<title>Test</title>
<style>
body {
margin: 0;
}
div {
margin: 3px auto 0;
width: 885px;
height: 610px;
border: 1px solid #f00;
background-color: #fdd;
}
</style>
</head>
<body>
<div>
This div is 885x610 (ratio is in between 4:3 and 16:10) with a 1px border and 3px top margin, making a total of 887x615.
</div>
</body>
</html>
What can I do to have this website scale to fit both the width and the height?

It's possible to get a consistent behavior. But it's unfortunately very complex. I am working on a script that detects spoofed agents and dynamically rescale the viewport to desktop or other spoofed agents accordingly. I was also facing the zooming issue with Android/Chrome as well as the iOS emulator...
To get around it, you need to disable zooming and/or set the viewport twice. On the first pass, preferably inline in the <head> as you do now, you set your scale and disable user-scaling temporarily to prevent the zoom issue, using the same fixed value for all 3 scales like:
document.querySelector('meta[name=viewport]').setAttribute('content', 'width='+width+',minimum-scale='+scale+',maximum-scale='+scale+',initial-scale='+scale);
Then to restore zooming you set the viewport again on DOMContentLoaded, with the same scale, except that this time you set normal min/max scale values to restore user-scaling:
document.querySelector('meta[name=viewport]').setAttribute('content', 'width='+width+',minimum-scale=0,maximum-scale=10');
In your context, because the layout is fixed and larger than the viewport, initial-scale='+scale is perhaps needed for a more sound alternative for DOMContentLoaded:
document.querySelector('meta[name=viewport]').setAttribute('content', 'width='+width+',minimum-scale=0,maximum-scale=10,initial-scale='+scale);
That should get the viewport to rescale as you would like in Webkit browsers without zooming problems. I say only in webkit because sadly IE and Firefox do not support changing the viewport as per this Browser Compatibility Table for Viewports, Dimensions and Device Pixel Ratios shows: http://www.quirksmode.org/mobile/tableViewport.html
IE has its own way to change the viewport dynamically which is actually needed for IE snap modes to be responsive.
http://timkadlec.com/2012/10/ie10-snap-mode-and-responsive-design/
So for IEMobile and IE SnapMode (IE10&11) you need to dynamically insert an inline <style> in the <head> with something like.
<script>
var s = document.createElement('style');
s.appendChild(document.createTextNode('#-ms-viewport{width:'+width+'px')+';}'));
document.head.appendChild(s);
</script>
And unfortunately, Firefox has neither: The viewport is set for once and for all as the above compatibility table shows. At the moment, for lack of other methods, using CSS Transform (as #imcg pointed out) is the only way to alter the viewport in FireFox Mobile on Android or Gecko OS. I have just tested it and it works in the context of a fixed size design. (In "Responsive Design context", the layout can be rescaled larger via CSS Transform, say at desktop size on a phone, but Firefox still read the phone size MQs. So that's something to be mindful off in RWD context. /aside from webkit)
Though, I have noticed some random Webkit crashes with CSSTransform on Android so I would recommend the viewport method for Safari/Chrome/Opera as more reliable one.
In addition, in order to get cross-browser reliability for the viewport width, you also have to face/fix the overall inconsistency between browsers for innerWidth (note that documentElement.clientWidth is much more reliable to get the accurate layout pixel width over innerWidth) and you also have to deal with devicePixelRatio discrepancies as indicated on the quirksmode.org table.
Update: Actually after some more thought into a solution for my own problem with Firefox, I just found out a way to override the viewport in Firefox Mobile, using document.write(), applied just once:
document.write('<meta name="viewport" content="width='+width+'px,initial-scale='+scale+'">');
Just tested this successfully in both Webkit and Firefox with no zooming issues. I can't test on Window Phones, so I am not sure itf document.write works for IEMobile...

I know this is two years late, but I spent a lot of time working on this problem, and would like to share my solution. I found the original question to be very helpful, so I feel that posting this answer is my way of giving back. My solution works on an iPhone6 and a 7" Galaxy Tab. I don't know how it fares on other devices, but I'm guessing it should mostly behave.
I separated the viewport logic into an external file so that it is easy to
reuse. First, here's how you would use the code:
<HTML>
<HEAD>
<SCRIPT type="text/javascript" src="AutoViewport.js"></SCRIPT>
</HEAD>
<BODY>
<SCRIPT>
AutoViewport.setDimensions(yourNeededWidth, yourNeededHeight);
</SCRIPT>
<!-- The rest of your HTML goes here -->
</BODY>
</HTML>
In actuality, I padded my desired width and height by a slight amount (15 pixels or so) so that my intended display was framed nicely. Also please note from the usage code that you do not have to specify a viewport tag in your HTML. My library will automatically create one for you if one does not already exist.
Here is AutoViewport.js:
/** Steven Yang, July 2016
Based on http://stackoverflow.com/questions/21419404/setting-the-viewport-to-scale-to-fit-both-width-and-height , this Javascript code allows you to
cause the viewport to auto-adjust based on a desired pixel width and height
that must be visible on the screen.
This code has been tested on an iPhone6 and a 7" Samsung Galaxy Tab.
In my case, I have a game with the exact dimensions of 990 x 660. This
script allows me to make the game render within the screen, regardless
of whether you are in landscape or portrait mode, and it works even
when you hit refresh or rotate your device.
Please use this code freely. Credit is appreciated, but not required!
*/
function AutoViewport() {}
AutoViewport.setDimensions = function(requiredWidth, requiredHeight) {
/* Conditionally adds a default viewport tag if it does not already exist. */
var insertViewport = function () {
// do not create if viewport tag already exists
if (document.querySelector('meta[name="viewport"]'))
return;
var viewPortTag=document.createElement('meta');
viewPortTag.id="viewport";
viewPortTag.name = "viewport";
viewPortTag.content = "width=max-device-width, height=max-device-height,initial-scale=1.0";
document.getElementsByTagName('head')[0].appendChild(viewPortTag);
};
var isPortraitOrientation = function() {
switch(window.orientation) {
case -90:
case 90:
return false;
}
return true;
};
var getDisplayWidth = function() {
if (/iPhone|iPad|iPod/i.test(navigator.userAgent)) {
if (isPortraitOrientation())
return screen.width;
else
return screen.height;
}
return screen.width;
}
var getDisplayHeight = function() {
if (/iPhone|iPad|iPod/i.test(navigator.userAgent)) {
if (isPortraitOrientation())
return screen.height;
else
return screen.width;
}
// I subtract 180 here to compensate for the address bar. This is imperfect, but seems to work for my Android tablet using Chrome.
return screen.height - 180;
}
var adjustViewport = function(requiredWidth, requiredHeight) {
if (/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent)){
var actual_height = getDisplayHeight();
var actual_width = getDisplayWidth();
var min_width = requiredWidth;
var min_height = requiredHeight;
var ratio = Math.min(actual_width / min_width, actual_height / min_height);
document.querySelector('meta[name="viewport"]').setAttribute('content', 'initial-scale=' + ratio + ', maximum-scale=' + ratio + ', minimum-scale=' + ratio + ', user-scalable=yes, width=' + actual_width);
}
};
insertViewport();
adjustViewport(requiredWidth, requiredHeight);
window.addEventListener('orientationchange', function() {
adjustViewport(requiredWidth, requiredHeight);
});
};
If you compare my code closely with the original code found in the question, you will notice a few differences. For example, I never rely on the viewport width or height. Instead, I rely on the screen object. This is important because as you refresh your page or rotate your screen, the viewport width and height can change, but screen.width and screen.height never change. The next thing you will notice is that I don't do the check for (ratio<1). When refreshing or rotating the screen, that check was causing inconsistency, so I removed it. Also, I included a handler for screen rotation.
Finally, I'd just like to say thank you to the person who created this question for laying the groundwork, which saved me time!

If you can't get consistent behavior across devices by changing the viewport meta tag, it's possible to zoom without changing the dimensions using CSS3 transforms:
if (ratio < 1) {
var box = document.getElementsByTagName('div')[0];
box.style.webkitTransform = 'scale('+ratio+')';
box.style.webkitTransformOrigin = '0 0';
}
console.log(box.offsetWidth); // always original width
console.log(box.getBoundingClientRect().width); // new width with scaling applied
Note I've omitted any vendor prefixes other than webkit here in order to keep it simple.
To center the scaled div you could use the translate tranforms:
var x = (actual_width - min_width * ratio) / 2;
var y = (actual_height - min_height * ratio) / 2;
box.style.webkitTransform = 'translateX('+x+'px) translateY('+y+'px) scale('+ratio+')';
box.style.webkitTransformOrigin = '0 0';

Replace your viewport with this :
<META NAME="viewport" CONTENT="width=device-width, height=device-height, initial-scale=1, user-scalable=no"/>
The user-scalable=0 here shall do the job for you.
This shall work for you.If it still doesn't work for we will have to extend the viewport so replace your viewport and add this:
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, target-densitydpi=medium-dpi, user-scalable=0" />
For your javascript error have a look at this link:
scale fit mobile web content using viewport meta tag

Set the height and width of the div's parent elements (html and body) to 100% and zero out the margin.
html, body {
margin: 0;
height: 100%;
width: 100%;
}
Next, because you want a border on the div you need to make sure that the border width is included when you specify the width / height of the element, to do this use box-sizing: border-box on the div.
Because you want a 3px top margin on the div relative positioning of the div will result in a height that is 3px too tall. To fix this use absolute positioning on the div and set top, left, and bottom to 0.
div {
position: absolute;
top: 3px;
left: 0;
bottom: 0;
box-sizing: border-box;
width: 100%;
border: 1px solid #f00;
background-color: #fdd;
}
Here's a working example.
UPDATE: I think I misunderstood the question. Here's a sample code that adjusts the "zoom" depending on the device's viewport
http://jpanagsagan.com/viewport/index2.html
Take note that I used jquery to append the meta tag as I am having issue using the vanilla append.
One thing I noticed is that if you hard-coded in the HTML and change it via JS, the document won't apply the correction (needs verification). I was able to change it via JS if there is no previous tag in the HTML, thus I used append.
You may play around with the ratio, but in the example I used width of the viewport divided by width of the div.
hope this helps.

UPDATE: I think I misunderstood the question. Here's a sample code that adjusts the "zoom" depending on the device's viewport
http://jpanagsagan.com/viewport/index2.html
Take note that I used jquery to append the meta tag as I am having issue using the vanilla append.
One thing I noticed is that if you hard-coded in the HTML and change it via JS, the document won't apply the correction (needs verification). I was able to change it via JS if there is no previous tag in the HTML, thus I used append.
You may play around with the ratio, but in the example I used width of the viewport divided by width of the div.
hope this helps.

I think Steven's should be the accepted answer.
In case it is helpful someone else, I would add the following 2 things to Steven's AutoViewport.js, in order to center the view within the viewport when the user is in landscape view:
Add "var viewport_margin = 0;" as the first line of code (as it's own line before "function AutoViewport() {}".
Add "viewport_margin = Math.abs(actual_width-(ratio*requiredWidth))/(actual_width*2)*100;" after the line that reads "document.querySelector('meta[name="viewport"]').setAttribute('content', 'initial-scale=' + ratio + ', maximum-scale=' + ratio + ', minimum-scale=' + ratio + ', user-scalable=yes, width=' + actual_width);"
Thanks for all those who posted to bring this solution to light.
UPDATE: In Android, my additions only appear to work with API 24+. Not sure why they aren't working with APIs 19-23. Any ideas?

Related

Scale website correctly on big monitors

I have a website that i'm working on locally, and it will be displayed through a projector for a presentation. Is there a way for me to scale it to the full size of the projection or if it were to be displayed on bigger screens without having to use all the media queries! I tried adding:
<meta name="viewport" content="initial-scale = 1.0,maximum-scale = 1.0" />
But i don't think it will do the trick! Any input from you is welcomed
Edit:
Just thought i'd add that the website is in a 1000*800 container on the original size, i just want it to grow a bit whenever a screen gets bigger
if using Bootstrap then wrapping all content in a container-fluid div will use the full screen width (and therefore projection width).
<div class="container-fluid">
...// content
</div>
I'd try getting the browser window resolution and setting the width and height accordingly if the resolution goes beyond a specific one.
<script>
function setContentSize(){
var ww = window.innderWidth;
var wh = window.innderHeight;
ID.style.width = 1000 +"px";
ID.style.width = 800 +"px"; //ID must be set in HTML
if(ww > what you want ){
ID.style.width = what you want +"px";
}
}
</script>
etc. You probably can work it out
And you can load it up with window.addEventListener("resize", setContentSize);
To auto-zoom the whole page, one solution is using transform: scale(). The page needs to sit inside a container for this to work. First set the origin in css for the container:
div#page-container {
transform-origin: 0 0;
}
Then change the scale factor with javascript (in my case jQuery):
$(function() {
var ratio = $('div#page-container').width() / $(document).width();
$('div#page-container').css('transform', 'scale(' + (1.0 / ratio) + ')');
});
Here is a Fiddle.

CSS "position:fixed": mobile zoom

I'm trying to solve an issue with css "position:fixed" property on mobile browsers. I have a fixed div:
<div id="logo">
...other content here...
</div>
with css:
#logo{
position: fixed;
-webkit-backface-visibility: hidden;
bottom: 100px;
right: 0px;
width: 32px;
height: 32px;
}
So, usually the behaviour is exactly the desired one, with the div position always on the bottom right of the window, indipendently of the scroll position.
My issue is that on mobile browsers, when the users zoom the page, after a certain zoom level the div position is wrong (sometimes the div disappear out of the window).
I know that fixed position is not well supported on mobile browsers, but I wonder if there is some workaround. I tried with this js code onScroll event:
window.addEventListener('scroll', function(e){
drag.style['-webkit-transform'] = 'scale(' +window.innerWidth/document.documentElement.clientWidth + ')';\\I want to avoid zoom on this element
var r = logo.getBoundingClientRect();
var w = window.innerWidth;
var h = window.innerHeight;
if(r.right != w){
rOff = r.right - w;
logo.style.right = rOff;
}
if(r.top+132 != h){\
tOff = r.top + 132 - h;
logo.style.bottom = tOff;
}
});
Unfortunately, the code seems to return the wrong position.
Does anyone have any tip?
Ok, that's how I solved the issue...I hope that could help anyone to simulate fixed position on iOS devices.
I switched the position from fixed to absolute;
Attach to window a listener to get the new position when the page is scrolled or zoomed,
setting window.onscroll and window.onresize events with the following function:
function position() {
drag.style.left = window.innerWidth + window.pageXOffset - 32 + 'px';
drag.style.top = window.innerHeight + window.pageYOffset - 132 + 'px';
}
Do you want to catch if zoom is active?
There's no window.onZoom listener, but you can read this thread:
Catch browser's "zoom" event in JavaScript
and this answer: https://stackoverflow.com/a/995967/3616853
There's no way to actively detect if there's a zoom. I found a good entry here on how you can attempt to implement it.
I’ve found two ways of detecting the zoom level. One way to detect zoom level changes relies on the fact that percentage values are not zoomed. A percentage value is relative to the viewport width, and thus unaffected by page zoom. If you insert two elements, one with a position in percentages, and one with the same position in pixels, they’ll move apart when the page is zoomed. Find the ratio between the positions of both elements and you’ve got the zoom level. See test case. http://web.archive.org/web/20080723161031/http://novemberborn.net/javascript/page-zoom-ff3
You could also do it using the tools of the above post. The problem is you're more or less making educated guesses on whether or not the page has zoomed. This will work better in some browsers than other.
There's no way to tell if the page is zoomed if they load your page while zoomed.
Just a theory, but you may want to try setting the bottom/right positions in % rather than px.
I think what you're seeing when using pixel measurements is just the zoom effecting the pixels. Or to put it better, when you zoom-in the pixels appear larger and that throws off the position of the element, even pushing it out of the view-port on smaller screens.
Example using pixel positioning
Notice that even on a desktop as you zoom-in and out the element appears to move up and down?
Example using percent positioning
In this example the element appears to stay in the bottom right corner, because it is always positioned at 10% from the bottom of the view-port.
#logo{
position: fixed;
-webkit-backface-visibility: hidden;
bottom:10%;
right: 0;
width: 32px;
height: 32px;
}
Having two different z-index for the logo and the rest of the page could help. Allowing zooming only to the rest of the page and not to the z-index layer where logo is included. So, this might not affect the stretching on the logo.
We can
Implement a ZOOM listener
Attach it to browser
Make the zoom listener change the zoom level of the element (modify the elements position) using z-index as a factor.

Get "visible" viewport zone after scaling

I use viewport in my web app, which enables scaling:
<meta name="viewport" content="width=device-width, initial-scale=1.0 ,maximum-scale=2.0" />
After zoom-in and zoom-out, I need to know what pixels are shown on the screen.
for example, when I use initial display I see 0 (div left) - 1024 (div right) pixels of my div (width), but after zoom-in, the area is different, because the div is "wider" and I see only a part of it.
Is there any way to calculate this data?
I tried using the scrollerLeft parameter (after zoom it is not "0"), but it returns 0 (seems like not updating).
you will get the width of the div
JS Fiddle
$(window).resize(function () {
findwidth()
})
findwidth()
function findwidth() {
var a = $('.left').width()
var b = $('.right').width()
var c = $(window).width()
$('.width1').html(a)
$('.width2').html(b)
$('.full').html(c)
}

Conditionally load JS script for Desktop PC (NOT touch device) with certain width only

On my website I use a JS for parallax scrolling. I want to conditionally load that JS only on Desktop PCs with >= 1025 px width. And I desperately need help with optimizing and putting it together.
What I currently have
The sections that have the Parallax-Effect have several data-attributes:
<section id="profile" class="slide" data-speed="2" data-offsetY="185" data-type="background">
The sections also have a background image set up via css.
.slide {
padding:0;
width:100%;
position:relative;
margin:0 auto;
overflow:hidden;
}
#profile {
background: url(../assets/backgrounds/02_profile_back.jpg) 50% 185px no-repeat fixed, #0f0f11;
height:1027px;
}
JAVASCRIPT
What I got so far:
Custom Function (myFunction) that's executed on $(document).ready
Check on window.on('scroll resize load')
Execute JS #breakpoint of 1025 px via enquire.js (match)
Set alternative / default behaviour (unmatch)
Use the listener of enquire.js.
Here's the code so far:
(The Parallax Script is: by Richard Shepherd, modified by Ryan Boudreaux)
function myFunction(){
// Cache the Window object
$window = $(window);
// Cache the Y offset and the speed of each sprite
$('[data-type]').each(function() {
$(this).data('offsetY', parseInt($(this).attr('data-offsetY')));
$(this).data('Xposition', $(this).attr('data-Xposition'));
$(this).data('speed', $(this).attr('data-speed'));
});
// For each element that has a data-type attribute
$('section[data-type="background"]').each(function(){
// Store some variables based on where we are
var $self = $(this),
offsetCoords = $self.offset(),
topOffset = offsetCoords.top;
// This is the part I'm having trouble with //
// When the window is scrolled, resized, loaded...
$(window).on('scroll resize load',function(e){
// Check if Screen-width is higher or equal to 1025px
enquire.register('screen and (min-width:1025px)', {
match : function() {
// If this section is in view
if ( ($window.scrollTop() + $window.height()) > (topOffset) &&
( (topOffset + $self.height()) > $window.scrollTop() ) ) {
// Scroll the background at var speed
// the yPos is a negative value because we're scrolling it UP!
var yPos = -($window.scrollTop() / $self.data('speed'));
// If this element has a Y offset then add it on
if ($self.data('offsetY')) {
yPos += $self.data('offsetY');
}
// Put together our final background position
var coords = '50% '+ yPos + 'px';
// Move the background
$self.css({ backgroundPosition: coords });
}; // in view
},
unmatch : function() {
$('#profile').css('background-position', '50% 0px');
}
}).listen(); // Check Screen Width
}); // window load resize scroll
}); // each data-type
} // myFunction
What I want to implement but cannot figure out
I'm looking for a way to squeeze in another if-loop, that only executes the first "match"-part if the device is NOT a Touch Device. I found var isTouch = (('ontouchstart' in window) || !!('msmaxtouchpoints' in window.navigator)); but I cannot figure out how to implement this so everything fits together.
Questions
Is there a way of realizing the condition "if desktop PC with 1025px and higher width"?
Is there a best practice / common solution for conditionally loading that parallax-JS at the end of mobile-first?
I know my code is a mess, you can probably tell by now that I'm a noob. Nevertheless, I'm eager to learn and am looking forward to your replies. Thanks a bunch!
Well you could use yepnope to load your JavaScript dynamically, and then use window.innerWidth to check the screen width. I'm not sure on checking specifically for a mobile device, unless you use browser user agent strings.

Getting the orientation dependent screen dimensions (IPad) in javascript

I am trying to get the screen dimensions on an IPad.
$wnd.screen.width
$wnd.screen.height
When I am in landscape mode, the dimensions return 768x1024. This is not what I expect. How can I get the real dimensions of 1024x768?
Note: I am not changing the orientation, I start in landscape mode and stay in that mode.
As the simplest solution, swap width and height if width is lesser than height so you always get the resolution of landscape mode.
function getResolution(){
return {
width: $wnd.screen.width < $wnd.screen.height
? $wnd.screen.height
: $wnd.scree.width,
height: $wnd.screen.height > $wnd.screen.width
? $wnd.screen.width
: $wnd.scree.height
};
}
The iPad likes to do funny things with scaling when you change orientation.
You can resolve many of those issues with a <meta viewport> tag, e.g.:
<meta name="viewport" content="user-scalable=no,initial-scale=1.0,
minimum-scale=1.0,maximum-scale=1.0">

Categories