Search code examples
javascriptviewportsvelte

Trigger a js function on orientationchangeend inside svelte:body


I want to display a message with a black background whenever the viewport orientation is portrait mode in svelte.

I used svelte-viewport-info to get the orientation of the viewport.

<script lang="ts">
  import Viewport from 'svelte-viewport-info'
  console.log('standard Screen Orientation: ',Viewport.Orientation)
</script>

<svelte:body
  on:orientationchangeend={() => { console.log(
    'Screen Orientation changed to: ', Viewport.Orientation + (
      Viewport.detailledOrientation == null
      ? ''
      : '(' + Viewport.detailledOrientation + ')'
    )
  ) }}
/>

I want to change the display property of a div

  • When in landscape mode, display set to none
  • When in portrait mode, display set to block

I found a js syntax to call function after a certain amount of time interval

var test = 0;
var interval;

function check_test() {
    if( test == 1 ){
        clearInterval( interval );
        console.log( "Test is 1 now!" );
    }
}

interval = window.setInterval( check_test, 1000 );

So inside this above function that is called every 1000 millisecond/1 second.

I found a syntax to use if statement in svelte here in #template-syntax-if

How do I perform all this in svelte it's along confusing

  1. I have to repeatedly call function using window.setInterval after certain interval
  2. Function needs to check the viewport Orientation from on:orientationchangeend inside svelte:body
  3. Use the if in svelte to set the display property of a div to block or none depending on the viewport Orientation from step 2

Solution

  • From the svelte-viewport-info docs

    CSS Classes In addition, the package also adds or removes the following CSS classes depending on the current device orientation:
    Portrait - indicates that the device is currently in any "Portrait" orientation
    Landscape - indicates that the device is currently in any "Landscape" orientation

    So you don't even have to track any event, you can simply use these classes to change the display of the div >> REPL
    (The compiler doesn't see any elements with the classes Landscape and Portrait, so the :global() modifier must be added so that they get compiled)

    <script context="module">
        import Viewport from 'svelte-viewport-info'
    </script>
    
    <div class="only-portrait">
        only visible in Portrait Mode
    </div>
    
    <style>
        :global(.Landscape .only-portrait) {
            display: none;
        }
        :global(.Portrait .only-portrait) {
            display: block;
            background: black;
            color: white;
            padding: 2rem;
        }
    </style>