skip to Main Content

Really new to Javascript, I have a code that I have to use inside an app that works fine for changing attributes reading width and height proportions.
I can now trigger this action and when the container show it will render the shape assigned, so it works ok.

In the app I can insert the function "On Show" on "Initialization" etc but not on resize or on orientation, so is not reading live Events and when a rotation happens or browser window resize, it won’t be listening to the change. If I close and reopen the container will be fine.

So I need to incorporate the listening to event.
Any Help?

this is my code:

var container = this.getComponentByName('Container_Name');
 const { clientWidth, clientHeight } = document.documentElement;

if (clientHeight > clientWidth) {
   container.set('width', 600);
   container.set('height', 300);
  } else {
   container.set('width', 220);
   container.set('height', 400);
  }

I need this function to run OnShow like already does and to run onOrientationChange()

Any help appreciated
onOrientationChange()

2

Answers


  1. Suggest you use the orientation CSS media feature to do this, rather than Javascript. It will be easier to implement and operate more reliably.

    When you run this snippet, make sure you use the full page link, then adjust your browser window into portrait and then landscape sizes to test the responsiveness.

    /* base styles specify what we want for portrait orientation */
    .morph {
      border: 2px solid red;
      width: 100px;
      height: 200px;
    }
    
    /* override styles for any changes we want for landscape orientation */
    @media (orientation: landscape) {
      .morph {
        width: 200px;
        height: 100px;
      }
    }
    <div class="morph"></div>
    Login or Signup to reply.
  2. To detect changes in orientation or resizing with JS, add an event listener.

    In your it would be a resize event.

    So it’ll look something like this:

    var container = this.getComponentByName('Container_Name'); 
    const { clientWidth, clientHeight } = document.documentElement;
    
    const resizeContainer = () => { 
      if (clientHeight > clientWidth) {
       container.set('width', 600);
       container.set('height', 300);
      } else {
       container.set('width', 220);
       container.set('height', 400);
      }
    }
    
    window.addEventListener('resize', e => resizeContainer());
    

    Here’s more info on JS event listeners: https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener

    However, if you’re just updating the container size, you’ll just need CSS to set the width and height and use JS to trigger CSS class toggle.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search