stamat/youtube-background

Body resize shifts the background iframe

azrossi opened this issue · 2 comments

I'm using this js for my site djalerossi.com

There are 4 sections with different heights that change without page refresh, nor window resize.

When I switched to a "taller" section/tab, the background shifted down to be vertically centred, leaving space above and below the background iframe.

I'm not an experienced programmer, but I found a quick-fix solution, and now the background iframe resizes correctly when the BODY element changes in size.

This is the part of the code I frankeinsteined (note that in my case I use the background as "cover", thus the bodyElement and not the more flexible parent element...)

if (this.params['fit-box']) {
  this.iframe.style.width = '100%';
  this.iframe.style.height = '100%';
} else {
  const self = this;
  const bodyElement = document.querySelector('body');

  //TODO❗️: maybe a spacer or at least add requestAnimationFrame
  function onResize() {
    const h = bodyElement.offsetHeight + self.params.offset; // since showinfo is deprecated and ignored after September 25, 2018. we add +200 to hide it in the overflow
    const w = bodyElement.offsetWidth + self.params.offset;
    const res = self.params.resolution_mod;
    if (res > w/h) {
      self.iframe.style.width = h*res + 'px';
      self.iframe.style.height = h + 'px';
    } else {
      self.iframe.style.width = w + 'px';
      self.iframe.style.height = w/res + 'px';
    }
  }

  const resizeObserver = new ResizeObserver(entries => {
    for (let entry of entries) {
      const h = bodyElement.offsetHeight + self.params.offset;
      const w = bodyElement.offsetWidth + self.params.offset;
      const res = self.params.resolution_mod;
      if (res > w/h) {
        self.iframe.style.width = h*res + 'px';
        self.iframe.style.height = h + 'px';
      } else {
        self.iframe.style.width = w + 'px';
        self.iframe.style.height = w/res + 'px';
      }
    }
  });

  resizeObserver.observe(bodyElement);
  window.addEventListener('resize', onResize);
  onResize();
}

For sure there are more sophisticated ways to code it, I'm more of a front-end developer/designer...

I hope this suggestion helps you fix the issue in a more elegant way.

Thanks

@azrossi you are too modest, that was a pro developer move ☺️ Thank you for the suggestion, I'll be sure to add it in the next version! I dig your DJing! 🙌

Thanks @stamat 😎