0

How to open modal if the screen orientation is "Portrait" and hide the modal if he orientation is "Landscape"

This is my current script.

But this is not working if the page loads in portrait mode initially..

<script>
    window.addEventListener("orientationchange", function() {
        if(screen.availHeight > screen.availWidth){
            $( '#oMsg' ).modal('show');  
        } else {
            $( '#oMsg' ).modal('hide');
        } 

    }, false);
    </script>

UPDATE

So I've updated my code as follows now with the help of Nitin and Naveen

<script>
    screen.orientation.addEventListener('change', function(e) {
        scrFunction();

    }, false);
    </script>
    <script>
    function scrFunction() {
        if(screen.availHeight > screen.availWidth){
            $( '#oMsg' ).modal('show');  
        } 
    }
    </script>

Also I changed my body

<body onload="scrFunction()">

But now my issues is even though it detects the orientation on page load, once I changed orientation back to Landscape, model remains there.. it's not removing..

2 Answers2

1

You can use <body onload="myFunction()">

(or)

add event "load" listener on document.

(or)

window.onload vs document.onload

Nitin Kumar
  • 1,448
  • 2
  • 13
  • 19
1

window.orientationchange is deprecated. Use the screen.orientation.onchange instead.

window.addEventListener('DOMContentLoaded', (event) => {

  toggleModalForScreen();

  screen.orientation.addEventListener('change', function(e) {
    toggleModalForScreen();
  });
});


function toggleModalForScreen() {
  if (screen.availHeight > screen.availWidth) {
    $('#oMsg').modal('show');
  } else {
    $('#oMsg').modal('hide');
  }
}

Documentation: https://w3c.github.io/screen-orientation/#screen-orientation-types-and-locks

naveen
  • 53,448
  • 46
  • 161
  • 251