I'm attempting to produce kind of like a Fullscreen experience while on landscape mode but nothing seems to work so far. I got a video that fakes going fullscreen mode as I have my own controls, unfortunately iOS doesn't support entering fullscreen on nothing except HTML5 <video> tags, so since I'm forced to use Fullscreen API and can't control those native buttons' visibility while on fullscreen state, I need to do something else which is faking it.
I want to produce the same effect as when going to "Aa button" on Search Bar > Hide Toolbar. It collapses everything and shows almost the entire screen space.
I tried going the CSS way or the window.scrollTo(0, 1) trick. Not working in my case as I have a fixed non-scrollable container holding the video and occupying the entire screen.
Also tried with this and many other codepens & jsfiddles on my Safari, none worked.
/*!
Intelligent auto-scrolling to hide the mobile device address bar
Optic Swerve, opticswerve.com
Documented at http://menacingcloud.com/?c=iPhoneAddressBar
*/
var bodyTag;
var executionTime = new Date().getTime(); // JavaScript execution time
// Document ready
//----------------
documentReady(function() {
// Don't hide address bar after a distracting amount of time
var readyTime = new Date().getTime()
if((readyTime - executionTime) < 3000) hideAddressBar(true);
});
// Run specified function when document is ready (HTML5)
//------------------------------------------------------
function documentReady(readyFunction) {
document.addEventListener('DOMContentLoaded', function() {
document.removeEventListener('DOMContentLoaded', arguments.callee, false);
readyFunction();
}, false);
}
// Hide address bar on devices like the iPhone
//---------------------------------------------
function hideAddressBar(bPad) {
// Big screen. Fixed chrome likely.
if(screen.width > 980 || screen.height > 980) return;
// Standalone (full screen webapp) mode
if(window.navigator.standalone === true) return;
// Page zoom or vertical scrollbars
if(window.innerWidth !== document.documentElement.clientWidth) {
// Sometimes one pixel too much. Compensate.
if((window.innerWidth - 1) !== document.documentElement.clientWidth) return;
}
// Pad content if necessary.
if(bPad === true && (document.documentElement.scrollHeight <= document.documentElement.clientHeight)) {
// Extend body height to overflow and cause scrolling
bodyTag = document.getElementsByTagName('body')[0];
// Viewport height at fullscreen
bodyTag.style.height = document.documentElement.clientWidth / screen.width * screen.height + 'px';
}
setTimeout(function() {
// Already scrolled?
if(window.pageYOffset !== 0) return;
// Perform autoscroll
window.scrollTo(0, 1);
// Reset body height and scroll
if(bodyTag !== undefined) bodyTag.style.height = window.innerHeight + 'px';
window.scrollTo(0, 0);
}, 1000);
}
// Quick address bar hide on devices like the iPhone
//---------------------------------------------------
function quickHideAddressBar() {
setTimeout(function() {
if(window.pageYOffset !== 0) return;
window.scrollTo(0, window.pageYOffset + 1);
}, 1000);
}
Any clue on how to produce this "fullscreen landscape" effect on mobile browser (Safari/Chrome) ?
I want to report the screen size of a mobile device and update on orientation change but am getting all sorts of strange errors e.g. width almost always 980px.
This works fine on desktop when resizing but not mobile (reporting landscape or portrait is fine though)
Tried on ipad, samsung galaxy tab, google nexus phone and iphone 4
Here's what I'm using:
// get dimensions
_getScreenWidth = function() {
var screenWidth = window.innerWidth;
var screenHeight = window.innerHeight;
var el = document.getElementById('dimensions');
_handleOrientation();
el.innerHTML = 'Width: '+screenWidth +' :: Height: '+screenHeight + "<br /><br />" + _doc_element.className;
};
// portait or landscape
_handleOrientation = function() {
if (device.landscape()) {
_removeClass("portrait");
return _addClass("landscape");
} else {
_removeClass("landscape");
return _addClass("portrait");
}
};
// resize event
var resizeTimeout;
window.onresize = function() {
clearTimeout(resizeTimeout);
// handle normal resize
resizeTimeout = setTimeout(function() {
_getScreenWidth();
}, 250); // 250ms delay
}
You will not get width in physical pixels. Instead, you'll receive "CSS pixels". This is why you getting strange errors. For orientation detecting, you can use "CSS pixels", just compare width to height.
I'm not sure what device.landscape() is supposed to be, but the device object doesn't exist, at least not in standard browsers.
all sorts of strange errors
In my case, that was due to undefined _addClass and _removeClass functions, _doc_element object and as mentioned above, device.landscape().
To fix device.landscape(), you can define landscape as a mode where width > height. Then it's just a simple comparison:
isLandscape = function() {
return window.innerWidth > window.innerHeight;
}
Here is example on jsfiddle with all of the errors fixed. Tested on iPhone 6 and it's setting correct classes.
There's a CSS file with these rules:
#media screen and (orientation:portrait) {
.foo {}
}
#media screen and (orientation:landscape) {
.foo {}
}
And then I've got this script, running on orientationchange:
function checkOr(){
if (window.matchMedia("(orientation:portrait)").matches) {
console.log('portrait ' + window.orientation);
} else {
console.log('landscape '+ window.orientation);
}
}
But matchMedia always returns initial state of the page, when window.orientation returns correct value:
portrait -90
portrait 0
portrait -90
Tested on iPhone 5 and iPad 4 with latest iOS updates.
What am I doing wrong?
Webkit bugtracker says that there must be rules for each media query, but that's not my case.
How are you adding the event to call the function on orientationchange? I just tried this on my iPad and it seems to work fine: http://jsbin.com/ewixuc/2
function checkOr(){
if (window.matchMedia("(orientation:portrait)").matches) {
alert('portrait ' + window.orientation);
} else {
alert('landscape '+ window.orientation);
}
}
window.addEventListener("orientationchange", checkOr);
Is it possible to detect change in orientation of the browser on the iPad or Galaxy Tab using javascript? I think it's possible using css media queries.
NOTE: orientationChange is deprecated
Instead use screen.orientation using the screenOrientation interface
var orientation = (screen.orientation || {}).type || screen.mozOrientation || screen.msOrientation;
if (orientation === "landscape-primary") {
console.log("That looks good.");
} else if (orientation === "landscape-secondary") {
console.log("Mmmh... the screen is upside down!");
} else if (orientation === "portrait-secondary" || orientation === "portrait-primary") {
console.log("Mmmh... you should rotate your device to landscape");
} else if (orientation === undefined) {
console.log("The orientation API isn't supported in this browser :(");
}
However note the support as of July 2022
The screen.orientation is not supported by Safari at all
Older answers
The older orientationChange should still work for Safari
window.addEventListener("orientationchange", function() {
alert(window.orientation);
}, false);
MDN:
window.addEventListener("orientationchange", function() {
alert("the orientation of the device is now " + screen.orientation.angle);
});
or jQuery mobile orientationchange
$(window).on("orientationchange", function( event ) {
$("#orientation").text( "This device is in " + event.orientation + " mode!");
});
Older answer
http://www.nczonline.net/blog/2010/04/06/ipad-web-development-tips/
Safari on the iPad does support the window.orientation property, so if necessary, you can use that to determine if the user is in horizontal or vertical mode. As reminder of this functionality:
window.orientation is 0 when being held vertically
window.orientation is 90 when rotated 90 degrees to the left (horizontal)
window.orientation is -90 when rotated 90 degrees to the right (horizontal)
There is also the orientationchange event that fires on the window object when the device is rotated.
You can also use CSS media queries to determine if the iPad is being held in vertical or horizontal orientation, such as:
<link rel="stylesheet" media="all and (orientation:portrait)" href="portrait.css">
<link rel="stylesheet" media="all and (orientation:landscape)" href="landscape.css">
http://www.htmlgoodies.com/beyond/webmaster/toolbox/article.php/3889591/Detect-and-Set-the-iPhone--iPads-Viewport-Orientation-Using-JavaScript-CSS-and-Meta-Tags.htm
<script type="text/javascript">
var updateLayout = function() {
if (window.innerWidth != currentWidth) {
currentWidth = window.innerWidth;
var orient = (currentWidth == 320) ? "profile" : "landscape";
document.body.setAttribute("orient", orient);
window.scrollTo(0, 1);
}
};
iPhone.DomLoad(updateLayout);
setInterval(updateLayout, 400);
</script>
You can use mediaMatch to evaluate CSS media queries, e.g.
window
.matchMedia('(orientation: portrait)')
.addListener(function (m) {
if (m.matches) {
// portrait
} else {
// landscape
}
});
CSS media query fires before the orientationchange. If you are looking to capture the end of the event (when the rotation has been completed), see mobile viewport height after orientation change.
In 2022, instead of adding a window orientationchange listener (listener not recommended due to deprecation) you should listen for a screen.orientation change event:
if (screen.orientation) { // Property doesn't exist on screen in IE11
screen.orientation.addEventListener("change", callback);
}
All browsers except IE and Safari now support it. (here is a screenshot of screen from IE11:
... notice that orientation is not a supported attribute of screen in IE11)
The Screen Orientation API is thoroughly documented. The main focus is the ScreenOrientation interface, which extends Screen. Here are 2 screenshots of the orientation attribute of Screen, which shows how the angle changes from 0 (portrait) to 90 (landscape) on an Android device:
You can use the orientationchange event like so:
window.addEventListener('orientationchange', function(event) {
/* update layout per new orientation */
});
I realized that nobody mentioned what happens when the device is held upside-down in this thread.
window.orientation returns -90 or 90 when held horizontal. It returns 0 or 180 when held vertical. Some devices do and some don't support being held upside-down. I recommend,
window.addEventListener("orientationchange", function() {
if ( window.orientation == 0 || window.orientation == 180) {
// WHEN IN PORTRAIT MODE
} else {
// WHEN IN LANDSCAPE MODE
}
}, false);
Also note that window.orientation returns undefined on desktops.
From "Cross-device, cross-browser portrait-landscape detection"
This is about finding out whether a mobile device is in portrait or landscape mode; you don't need to care about its orientation. For all you know, if you hold your iPad upside down, it's in portrait mode.
$(window).bind("resize", function(){
screenOrientation = ($(window).width() > $(window).height())? 90 : 0;
});
90 means landscape, 0 means portrait, cross browser, cross device.
The window.onresize event is available everywhere, and it's always fired at the right time; never too early, never too late. As a matter of fact, the size of the screen is always accurate as well.
The JavaScript version would be this, correct me please if I am wrong.
function getScreenOrientation() {
screenOrientation = window.outerWidth > window.outerHeight ? 90 : 0;
console.log("screenOrientation = " + screenOrientation);
}
window.addEventListener("resize", function(event) {
getScreenOrientation();
});
getScreenOrientation();
window.orientation is what you're looking for. there's also an onOrientationChange event
works for android, iphone and, i'm mostly sure, for ipad
Adding to the #mplungjan answer, I found better results using the webkit "native" (I don't really how to called it) event, 'deviceorientation'.
In the Mozilla Developer network they have a good explanation about how to normalize between webkit and Gecko that helped me to solve this problem.
An easy to use snippet :
function doOnOrientationChange()
{
switch(window.orientation)
{
case -90:
case 90:
// alert('landscape');
$('#portrait').css({display:'none'});
$('#landscape').css({display:'block'});
break;
default:
// alert('portrait');
$('#portrait').css({display:'block'});
$('#landscape').css({display:'none'});
break;
}
}
window.addEventListener('orientationchange', doOnOrientationChange);
// First launch
doOnOrientationChange();
orientationChange is deprecated and also not supported in some browsers,
innerHeight and outerHeight sometimes give inconsistent results in ios
so we can use document.documentElement to check orientation along with resize event
const { clientWidth, clientHeight } = document.documentElement;
if (clientHeight > clientWidth) {
setOrientation("portrait-secondary");
} else {
setOrientation("landscape-primary");
}
As of 2022
Once you get ready like this,
let theDeviceIsRotated;
function handlePortraitOrLandscape() {
setTimeout(afterAnUnnoticableDelay,100); // This solves the wrong-firing-order issue on Samsung Browser.
function afterAnUnnoticableDelay() {
if (screen.orientation) { // Mainly for Android (as of 2022)
// Returns 0 or 90 or 270 or 180
if (screen.orientation.angle == 0) { theDeviceIsRotated="no"; }
if (screen.orientation.angle == 90) { theDeviceIsRotated="toTheLeft"; }
if (screen.orientation.angle == 270) { theDeviceIsRotated="toTheRight"; }
if (screen.orientation.angle == 180) { theDeviceIsRotated="upsideDown"; }
} else { // Mainly for iOS (as of 2022)
// Returns 0 or 90 or -90 or 180
if (window.orientation == 0) { theDeviceIsRotated="no"; }
if (window.orientation == 90) { theDeviceIsRotated="toTheLeft"; }
if (window.orientation == -90) { theDeviceIsRotated="toTheRight"; }
if (window.orientation == 180) { theDeviceIsRotated="upsideDown"; }
}
}
}
handlePortraitOrLandscape(); // Set for the first time
window.addEventListener("resize",handlePortraitOrLandscape); // Update when change happens
you can
if (theDeviceIsRotated == "no") {
// Do your thing
} else if (theDeviceIsRotated == "toTheLeft") {
// Do your thing
} else if (theDeviceIsRotated == "toTheRight") {
// Do your thing
} else if (theDeviceIsRotated == "upsideDown") {
// Do your thing
} else {
// The mysterious 5th orientation nobody has ever seen yet
}
but note that
RESIZE does not fire when switching from 90 to 270 directly (without triggering a portrait view in between)
THEREFORE WE CANNOT RELY ON
window.addEventListener("resize",screenOrientationHasChanged);
AND THERE IS THE EXACT SAME PROBLEM WITH
window.screen.orientation.addEventListener('change',screenOrientationHasChanged);
ALSO WITH
window.addEventListener("orientationchange",screenOrientationHasChanged);
THIS SADLY MEANS THAT AS OF 2022 THERE IS NO RELIABLE WAY TO DETECT SCREEN ORIENTATION CHANGE even by using setInterval
BECAUSE neither screen.orientation.angle nor screen.orientation.type is updated when you go from 90 to 270 without triggering a portrait view in between.
So the following is not any better than resize on mobile devices
if (screen.orientation) {
window.screen.orientation.addEventListener('change',screenOrientationHasChanged); // https://whatwebcando.today/screen-orientation.html
} else {
window.addEventListener("orientationchange",screenOrientationHasChanged); // https://developer.mozilla.org/en-US/docs/Web/API/Window/orientationchange_event
}
You may try to lock the screen orientation to avoid errors but that does not work on iOS as of 2022 and it only works with fullscreen mode on Android.
I have a scrolling function over a recursive TimeOut making a very width window scroll horizontally until it reaches the right end, but I need to know in JavaScript if the scrolling has finished to change the direction and scroll back to the origin.
How can I accomplish this?
function ScrollIt(scrollPos, direction) {
if(direction == 'right')
window.scrollBy(scrollPos,0);
else
window.scrollBy(scrollPos,0);
cTimeOut = setTimeout("ScrollIt(1,'right')",10);
}
Of course I call the function in the onload event the first time.
Thanks in advance.
var w = document.documentElement.clientWidth;
var over = document.documentElement.scrollWidth - w;
window.onscroll = function() {
// Detect webkit browser (Chrome, Safari)
if(window.devicePixelRatio) {
if(document.body.scrollLeft==over) { alert("KABOOM (Webkit)") }
}
else {
if(document.documentElement.scrollLeft == over) { alert("CRUNCH") }
}
}
Tested FF 3.6, IE8, Chrome 3.1, Safari 4.0