Detect change in orientation using javascript
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 :(");
}
How to detect orientation change?
Here's how I got it working:
In AppDelegate.swift
inside the didFinishLaunchingWithOptions
function I put:
NotificationCenter.default.addObserver(self, selector: #selector(AppDelegate.rotated), name: UIDevice.orientationDidChangeNotification, object: nil)
and then inside the AppDelegate class I put the following function:
func rotated() {
if UIDeviceOrientationIsLandscape(UIDevice.current.orientation) {
print("Landscape")
}
if UIDeviceOrientationIsPortrait(UIDevice.current.orientation) {
print("Portrait")
}
}
Hope this helps anyone else!
Thanks!
Swift - How to detect orientation changes
let const = "Background" //image name
let const2 = "GreyBackground" // image name
@IBOutlet weak var imageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
imageView.image = UIImage(named: const)
// Do any additional setup after loading the view.
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
if UIDevice.current.orientation.isLandscape {
print("Landscape")
imageView.image = UIImage(named: const2)
} else {
print("Portrait")
imageView.image = UIImage(named: const)
}
}
How to detect orientation change in layout in Flutter?
In order to determine the Orientation of the screen, we can use the OrientationBuilder
Widget. The OrientationBuilder will determine the current Orientation and rebuild when the Orientation changes.
new OrientationBuilder(
builder: (context, orientation) {
return new GridView.count(
// Create a grid with 2 columns in portrait mode, or 3 columns in
// landscape mode.
crossAxisCount: orientation == Orientation.portrait ? 2 : 3,
);
},
);
you can find the complete example here:
https://flutter.io/cookbook/design/orientation/
How to detect orientation change in layout in Android?
Use the onConfigurationChanged method of Activity.
See the following code:
@Override
public void onConfigurationChanged(@NotNull Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Checks the orientation of the screen
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
}
}
You also have to edit the appropriate element in your manifest file to include the android:configChanges
Just see the code below:
android:configChanges="orientation|keyboardHidden"
android:label="@string/app_name">
NOTE: with Android 3.2 (API level 13) or higher, the "screen size" also changes when the device switches between portrait and landscape orientation. Thus, if you want to prevent runtime restarts due to orientation change when developing for API level 13 or higher, you must declare android:configChanges="orientation|screenSize" for API level 13 or higher.
Hope this will help you... :)
Is there any window event for orientation change using @HostListener like we have @HostListener(window:scroll, ['$event']) for scrolling?
From MDN; you can use window:orientationchange
to detect when the orientation of the device has changed.
@HostListener('window:orientationchange', ['$event'])
onOrientationChange(event) {
console.log('orientationChanged');
}
Here is a short clip to see this in action in Chrome Dev Tools: https://streamable.com/o2ilm
Detect viewport orientation, if orientation is Portrait display alert message advising user of instructions
if(window.innerHeight > window.innerWidth){
alert("Please use Landscape!");
}
jQuery Mobile has an event that handles the change of this property... if you want to warn if someone rotates later - orientationchange
Also, after some googling, check out window.orientation
(which is I believe measured in degrees...)
EDIT: On mobile devices, if you open a keyboard then the above may fail, so can use screen.availHeight
and screen.availWidth
, which gives proper height and width even after the keyboard is opened.
if(screen.availHeight > screen.availWidth){
alert("Please use Landscape!");
}
How to detect device orientation with JavaScript?
There are two ways to do this:
First, as per the Screen API documentation, using >= Chrome 38, Firefox, and IE 11, the screen object is available to not only view the orientation, but to also register the listener on each time the device orientation changes.
screen.orientation.type
will explicitly let you know what the orientation is, and for the listener you can use something simple like:
screen.orientation.onchange = function (){
// logs 'portrait' or 'landscape'
console.log(screen.orientation.type.match(/\w+/)[0]);
};
Second, for compatibility with other browsers like Safari that aren't compatible with Screen, this post shows that you can continue to use innerWidth and innerHeight on window resizing.
function getOrientation(){
var orientation = window.innerWidth > window.innerHeight ? "Landscape" : "Portrait";
return orientation;
}
window.onresize = function(){ getOrientation(); }
Related Topics
Why Nsuserdefaults Failed to Save Nsmutabledictionary in Ios
Stringbyappendingpathcomponent Is Unavailable
#Warning: C-Style For Statement Is Deprecated and Will Be Removed in a Future Version of Swift
How to Compare Two Uiimage Objects
Watchkit Extension - No Matching Provisioning Profiles Found
Calling a Phone Number in Swift
Nsphotolibraryusagedescription Key Must Be Present in Info.Plist to Use Camera Roll
How to Load Storyboard Programmatically from Class
How to Pass Data Between View Controllers in Swift
Anyobject Not Working in Xcode8 Beta6
Xcode, Where to Assign the Segue Identifier
Swift - How to Get the File Path Inside a Folder
How to Handle Background Audio Playing While iOS Device Is Locked or on Another Application
Background-Size: Cover Not Working on iOS
Ios: How to Change App Language Programmatically Without Restarting the App