8

The orientationchange event has been deprecated.

window.addEventListener("orientationchange", function(event) {
  console.log(event.target.screen.orientation.angle);
});

Window: orientationchange event

Deprecated This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

What can I use now? Is there any alternative way to do this?

Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231

2 Answers2

6

We can use experimental feature ScreenOrientation

screen.orientation.addEventListener('change', function(e) { ... })
screen.orientation.onchange = function(e) { ... }

You can check the available values from screen orientation table for orientation types:

  • portrait-primary
  • portrait-secondary
  • landscape-primary
  • landscape-secondary

Here's an example:

screen.orientation.addEventListener('change', function(e) {
  if (e.currentTarget.type === 'landscape-primary') {
    // landscape mode => angle 0
  } else if (e.currentTarget.type === 'portrait-primary') {
    // portrait mode => angle 0
  }
})

Check browser compatibility table.

Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231
0

window.orientation

Still seems to work. I guess you can use

window.addEventListener('resize', function(e) {
  if (Math.abs(window.orientation) == 90) {
    // landscape mode => angle 90 or -90
  } else if (window.orientation == 0) {
    // portrait mode => angle 0
  }
})

If you your target is strictly mobile

Kendall
  • 5,065
  • 10
  • 45
  • 70
  • 2
    It is deprecated only not removed. in future it will be removed. – Bhojendra Rauniyar Feb 08 '22 at 06:37
  • 1
    I don't think it ever will. It will remain one of those deprecated apis that are never put away for good because it already has so much adoption. Nobody cares if it's deprecated, it's good and it works as expected, so everybody uses it. – savram Dec 03 '22 at 16:12