Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect orientation change in Ionic App

I've tried with events, but that doesn't work.

document.addEventListener('onorientationchange', function() 
   {...}
);

I know how to get the orientation of the screen, but i didn't find out how to detect when the orientation changes.

like image 813
Kreepz Avatar asked Jun 04 '26 17:06

Kreepz


2 Answers

Pleas try this one:

angular.module('starter', ['ionic'])

.run(function($ionicPlatform) {
  $ionicPlatform.ready(function() {
    ...
    window.addEventListener("orientationchange", function() {
      console.log(window.orientation);
    }, false);  
  });
})
like image 124
Andre Kreienbring Avatar answered Jun 06 '26 06:06

Andre Kreienbring


First you need to install the cordova-plugin-screen-orientation plugin:

For cordova < 4 run:

cordova plugin add net.yoik.cordova.plugins.screenorientation

For cordova > 4 run:

cordova plugin add cordova-plugin-screen-orientation

The plugin adds the following to the screen object (window.screen):

// lock the device orientation
.lockOrientation('portrait')

// unlock the orientation
.unlockOrientation()

// current orientation
.orientation

Now you can use something like the following to detect the orientation of the screen:

window.addEventListener("orientationchange", function(){
    console.log(screen.orientation); // e.g. portrait
});

See https://github.com/gbenvenuti/cordova-plugin-screen-orientation for more information/documentation

like image 30
Joel Brewer Avatar answered Jun 06 '26 08:06

Joel Brewer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!