Search code examples
ionic-frameworkorientationdetect

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.


Solution

  • 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