Force page zoom at 100% with JS - javascript

I created a little game in Canvas, but I have a problem. Some users who have the default zoom set to something other than 100% can't see the entire game page.
I have tried using this CSS:
zoom: 100%;
This HTML
<meta name="viewport" content="initial-scale=1.0 , minimum-scale=1.0 , maximum-scale=1.0" />
And this JS:
style="zoom: 75%"
Any ideas how to programatically set the page zoom?

You can set zoom property on page load
document.body.style.zoom = 1.0
But, zoom is not a standard property for all browsers, I recommend using transform instead.
var scale = 'scale(1)';
document.body.style.webkitTransform = scale; // Chrome, Opera, Safari
document.body.style.msTransform = scale; // IE 9
document.body.style.transform = scale; // General
http://jsfiddle.net/5RzJ8/

You can reset the code with this:
$("input, textarea").focusout(function(){
$('meta[name=viewport]').remove();
$('head').append('<meta name="viewport" content="width=device-width, maximum-scale=1.0, user-scalable=0">');
$('meta[name=viewport]').remove();
$('head').append('<meta name="viewport" content="width=device-width, initial-scale=yes">' );
});

I think, this is very helpful answer how to detect page zoom level in all modern browsers. Then the answer to your question for IE:
document.body.style.zoom = screen.logicalXDPI / screen.deviceXDPI;

It is working in chrome 66 :
document.body.style.zoom = (window.innerWidth / window.outerWidth)

The only way I found that works natively is in designing my HTML/CSS with the units "vw" and "vh" (% relative to the viewport) instead of "px". You can use it everywhere you used to put "px" (font-size, width, height, padding, margin, etc...). Very useful for a page designed to be display full screen only (no scroll) or "Kiosk-style". "vw" and "vh" are not affected by browser zoom.
See: https://www.w3schools.com/cssref/css_units.asp

For mobile browsers, #Linden's answer worked the best for me on Chrome. However on mobile FF it needed some additional tweaks, I came to version that works in both browsers:
let restore = $('meta[name=viewport]')[0];
if (restore) {
restore = restore.outerHTML;
}
$('meta[name=viewport]').remove();
$('head').append('<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">');
if (restore) {
setTimeout(() => {
$('meta[name=viewport]').remove();
$('head').append(restore);
}, 100); // On Firefox it needs a delay > 0 to work
}
Also, the restored page viewport tag must have explicit maximum-scale to allow zooming on Firefox after resetting, so I set it initially to this:
<meta name="viewport" content="width=device-width, maximum-scale=10">
Tested on mobile Chrome 76.0 and mobile Firefox 68.1.

I'd try both solutions but the following is seems to be a bug in echarts which leads to cursor deviated.
document.body.style.zoom = 1.25; // work but not to be expected.
I wonder if there any solution for the browser to directly modify the zoom ratio just like what ctrl++/- effect.

Related

Quick help scaling a website

I try to set the initial scale of this website.
I tried this:
document.body.style.zoom = '0.8';
and this:
document.body.style.webkitTransform = 'scale(0.8)';
Unfortunatelly the slider of the timeperiod-bar looses it´s functionality. Does anyone know a workaraound for that? Thanks everyone for ideas.
UPDATE: New approach:
var metaTag=document.createElement('meta');
metaTag.name = "viewport"
metaTag.content = "width=device-width, initial-scale=0.8, maximum-scale=0.8, user-scalable=0"
document.getElementsByTagName('head')[0].appendChild(metaTag);
Here, nothing happens at all.
EDIT: Another approach:
document.querySelector("meta[name=viewport]").setAttribute(
'content',
'width=device-width, initial-scale=0.8, user-scalable=no');
unfortunately no success.
To set the initial scale, you need to adjust your viewport in the meta.
Currently , your meta tag sets the scale to 1
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
Change the 1.0 to 0.8 and it should adjust accordingly.
<meta name="viewport" content="width=device-width, initial-scale=0.8" />
For what it's worth, I resized it using my browser window, and the zoom still worked fine when I clicked on the buttons.
(The bar doesn't seem to work even at full screen; I have a 15" laptop and the bar slider didn't work, but the buttons work; you can maybe hide the bar?)
Hope this helps
EDIT
The allowable values for user-scalable are yes or no, not 0 and 1.
Set user-scalable to no if you want it to be non-scalable. Also set the initial-scale as well as the maximum-scale
RE-EDIT
see https://stackoverflow.com/a/9232064/1675954 for how to edit meta tags using jquery
The javascript solution: follow this syntax
document.querySelector('meta[name="viewport"]').setAttribute("content", _desc);
See this article also for updating for media queries
Chrome Window Resizer has been a life saver checking if webpages works across all platforms.
https://chrome.google.com/webstore/detail/window-resizer/kkelicaakdanhinjdeammmilcgefonfh?hl=en

Disable pinch zoom in webkit (or electron)

Is there any way to disable pinch zoom in an electron app?
I can't get it to work from inside the web-view with normal javascript methods as described here: https://stackoverflow.com/a/23510108/665261
It seems the --disable-pinch flag is not supported by electron.
I have experimented with various methods using:
event.preventDefault() on javascript touchmove/mousemove events
meta viewport tags in HTML
-webkit-text-size-adjust in CSS
flags/config for electron
Is there any method either for webkit in general, or electron in particular?
UPDATE 2:
Use webFrame.setZoomLevelLimits (v0.31.1+) in render process (Differences Between Main Process and Renderer Process). Because smart zoom on mac still work with document.addEventListener.
Example require('electron').webFrame.setZoomLevelLimits(1, 1)
UPDATE:
deltaY property for pinch zoom has float value, but normal scroll event return int value. Now solution has no problem with ctrl key.
Demo 2.
document.addEventListener('mousewheel', function(e) {
if(e.deltaY % 1 !== 0) {
e.preventDefault();
}
});
Using Chromium monitorEvents(document) I found that is responsible for this event mousewheel. I don't know, why mousewheel triggered with pinch zoom.
Next step, find difference between normal scroll and pinch zoom.
Pinch zoom has an attribute e.ctrlKey = true, and normal scroll event has e.ctrlKey = false. But if you hold down ctrl key and scroll a page, e.ctrlKey equal true.
I couldn't find a better solution. :(
Demo
document.addEventListener('mousewheel', function(e) {
if(e.ctrlKey) {
e.preventDefault();
}
});
It seems very difficult for desktop browser to prevent pinch zoom.
Here are some ideas though!
1) By using some gestures javascript like hammer.js, detect Pinch event and try to prevent it using e.preventDefault
OR
2) Design everything using "%" in css, or use newer units like "vm" etc, (if possible). This way, even page will be zoomed, but content will stay the same for any zoom level.
All the best!
Answer from GitHub:
"If you are looking for a way how to prevent zoom from main process, you can use:"
const webContents = mainWindow.webContents;
webContents.on('did-finish-load', () => {
webContents.setZoomFactor(1);
webContents.setVisualZoomLevelLimits(1, 1);
webContents.setLayoutZoomLevelLimits(0, 0);
});
mainWindow is variable where you have new BrowserWindow, e.g.:
const mainWindow = new BrowserWindow({
width: 440,
height: 750,
// ...
});
const webContents = mainWindow.webContents;
webContents.on("did-finish-load", () => {
webContents.setZoomFactor(1);
webContents.setVisualZoomLevelLimits(1, 1);
webContents.setLayoutZoomLevelLimits(0, 0);
});
Is there a reason why you can't use:
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0"/>
Put that in the header and it keeps devices from zooming.
I searched so long and hard for a simple solution to this problem with no avail...but later I discovered a plugin called fullpage.js that was able to prevent pinch zoom while still allowing touch gestures. Through the process of js/css elimination, I discovered a very simple solution:
touch-action: none;
Adding this to my full page element successfully prevented pinch zoom but allowed me to scale fabricjs objects with pinching. Hooray !
var app = require('electron')
app.commandLine.appendSwitch('disable-pinch');
Solution found by mixing these two links:
1 - https://github.com/electron/electron/issues/8793#issuecomment-289791853
2 - https://github.com/electron/electron/blob/master/docs/api/chrome-command-line-switches.md
I had to set { passive: false } to make it work. Don't ask me why.
window.addEventListener('wheel', (e) => {
if(e.ctrlKey) e.preventDefault();
}, { passive: false });
meta tag should have worked. Try using the minimum-scale=1.0
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, user-scalable=no">
And if it also not works then add both the minimum and maximum scale
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
P.S. : It will disable zooming on mobile phones only.
I got the easiest fix for this, in the index.html or similar file for your project, within the script tag, include electron and configure zoom level as below,
<script>
const electron = require('electron'); // Include electron
electron.webFrame.setZoomLevelLimits(1, 1); // Set min max zoom level as 1
const { ipcRenderer } = electron;
...
</script>
This works perfectly fine across devices.
The viewport meta tag approach doesn't work well on desktop, only fixes issue on mobile devices.

HTML5 Javascript issue

I am having strange issue, I had developed an mobile application using HTML5, it is working fine in Android phones but it is not working in iPhone, the javascript is completely ignored in all iPhones, in iPhone Javascript is enabled but still not working.
This is the site that I developed http://trafficticket.net23.net/mobile.html I have another problem also, the site is NOT taking up 100% width of the screen in Android, in Viewport I had given like this
<meta name="viewport" content="width=device-width, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
<script type="text/javascript">
var viewPortWidth = 1024;
function setViewport() {
if ((navigator.userAgent.toLowerCase().indexOf("android")!=-1)) {
var wW0 = window.screen.width;
var scale = wW0/viewPortWidth;
var vPort = "width="+viewPortWidth+", maximum-scale="+scale+", minimum-scale="+scale+", initial-scale="+scale+", user-scalable=yes";
document.getElementById("viewport").setAttribute("content", vPort);
}
}
setViewport();
</script>
But top strip is not taking up 100% width of the mobile screen.
What mistake I am doing ..
The if statement is excluding iPhones:
if ((navigator.userAgent.toLowerCase().indexOf("android")!=-1)) {
This will never be true on an iphone

How to make my simple website-quiz fittable to tablets and mobile phones?

how could I make my simple website-quiz fittable to tablets and mobile phones? The size of the quiz is 1024x672 in landscape mode. The size is static. If there's no bullet-proof solution for all devices, I would prefer a solution specific for iPhones and iPads.
Here's the quiz: http://wp.servitus.ch
Requirements:
auto-zoom dependent of current screen-size of the device
user should not be able to zoom manually
possible to force landscape mode ?
I already experimented with:
<meta name="viewport" content="initial-scale=1,user-scalable=no,maximum-scale=1,width=device-width">
This works fine for iPads, but is way too large on the iPhone.
Any ideas ?
Currently I am using the code below. This meets my requirements for the moment (distinction between iPad, iPhone, Computer). If anyone has a bullet-proof solution for all possible devices, I would be glad if you would share it with me :-) Thanks!
$(document).ready(function() {
var isMobile = (/iPhone|iPod|Android|BlackBerry/).test(navigator.userAgent);
var isTablet = (/iPad/).test(navigator.userAgent);
if(isMobile) {
$('<meta name="viewport" content="initial-scale=0.45, maximum-scale=0.45, width=device-width, user-scalable=yes">').appendTo('head');
} else if(isTablet) {
$('<meta name="viewport" content="initial-scale=0.95, maximum-scale=0.95, width=device-width, user-scalable=no">').appendTo('head');
} else {
$('<meta name="viewport" content="initial-scale=1, maximum-scale=1, width=device-width, user-scalable=no">').appendTo('head');
}
});
This meta viewport can't help you, as the initial-scale is 1. That's why it's way too big for iPhone: you tell the device that the initial scale of this page must be 100% of its size (here : 1024px width), you have to remove this parameter or set it lower (0.5 or 0.625, as 640/1024 = 0.625).
Try with (this should work for iPhone and iPad) :
<meta name="viewport" content="width=device-width">
or (this should be very small on iPad) :
<meta name="viewport" content="initial-scale=0.6,user-scalable=no,maximum-scale=1,width=device-width">
EDIT :
This should work :
<meta name="viewport" content="width=1024">
I used that trick on a mobile website that haven't been well coded, it forces the viewport to 1024 and make it fit in the device screen. You can add whatever parameters to the meta.

Is there a way to reset the scale of the viewport dynamically to 1.0

Im working on a a mobile online-store And got stuck while implementing the product zoom function
After clicking an Image "user-scalable" is allowed and maximum-scale is set to 10.0
When the user zooms in on the product with a pinch gesture, everything works fine.
But after closing the zoomed Image the scale is not reset to 1.0.
Is there a way to reset the scale value of the viewport dynamically.
The "initial-scale" seems not to work, neither does reseting the "minimum-scale" and "maximum-scale" to 1.0
The problems occurs on iPhone / iPad
There seems to be a solution, but i don't know to which element i should apply the on this post:
How to reset viewport scaling without full page refresh?
"You need to use -webkit-transform: scale(1.1); webkit transition."
But I don't know to which element the style is applied.
Here is some code to illustrate the Problem.
In the meta Tag for the viewport looks like this:
<meta name="viewport" content="user-scalable=no, width=device-width, height=device-height, minimum-scale=1.0, maximum-scale=1.0" />
the rest of the page Looks like this:
<div id="page">
<img src="images/smallProductImage.jpg">
</div>
<div id="zoom">
<div class="jsZoomImageContainer"></div>
</div>
and this is the javascript::
zoom:{
img: null,
initialScreen:null,
load:function(src){
//load the image and show it when loaded
showLoadingAnimation();
this.img = new Image();
this.img.src = src;
jQuery(this.img).load(function(){
zoom.show();
});
},
show:function(){
var screenWidth, screenHeight, imageWidth, imageHeight, scale, ctx;
hideLoadingAnimation();
jQuery("#page").hide();
jQuery("#zoom").show();
jQuery(".jsZoomImageContainer").empty();
this.initialScreen =[jQuery(window).width(), jQuery(window).height()]
jQuery(".jsZoomImageContainer").append(this.img);
imageWidth = jQuery(this.img).width();
imageHeight = jQuery(this.img).height();
scale = this.initialScreen[0] / imageWidth ;
jQuery(this.img).width(imageWidth * scale)
jQuery(this.img).height(imageHeight * scale)
jQuery(".jsZoomImageContainer").click(function(){
zoom.hide();
});
jQuery('meta[name="viewport"]',"head").attr("content","user-scalable=yes, initial-scale:1.0, minimum-scale=1.0, maximum-scale=10.0")
},
hide:function(){
jQuery(".jsZoomImageContainer").empty();
jQuery('meta[name="viewport"]',"head").attr("content","user-scalable=no, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0")
jQuery("#zoom").hide();
jQuery("#page").show();
this.img = null;
this.initialScreen = null;
}
}
jQuery("#page img").click(function(){
zoom.load("images/bigProductImage.jpg");
});
According to ppk, this technique for viewport manipulation works on all modern browsers except for Firefox:
<meta id="testViewport" name="viewport" content="width = 380">
<script>
if (screen.width > 740) {
var mvp = document.getElementById('testViewport');
mvp.setAttribute('content','width=740');
}
</script>
Seems like the key is setting an id attribute in the meta tag so you can select it easily with JS and replace the value of the content attribute.
It works in all modern browsers. I have done it in a few websites and all work fine.
But resetting is not a solution to the problem. You need to properly change scale and viewport width when circumstances change.
You need to change it when orientation changes and when screen size changes and of course on load when screen size is detected. If you get values for current width, you can calculate the scale. (By the way, when orientation is 90 or -90, you should take height as width).
For example,
If your main container is 960px in width, and w_width is the current width you get dynamically.
scale=100/100/(960/w_width);
scale=scale.toFixed(2) ;
jQuery('meta[name=viewport]').attr('content', "width="+w_width+", initial-scale="+scale);

Categories