0

I would like to achieve the following:

On a mobile device, when someone starts scrolling from the top, a text starts to shrink down, and after a given amount, it takes its final size and stays like so for the rest of the page. The idea is that I have a Company name in the middle of the screen, and on scroll, it shrinks to the top left corner of the screen, and a menu bar appears behind it, and the Company name becomes the logo on the menu bar. The menu bar's background is the Hero image of the page. Here is my code:

window.onscroll = scrolled
function scrolled(){
  let fromTop = window.scrollY
  if (fromTop < 300) {
    heroText.style.fontSize = `${2 - fromTop/160}em`
    hero.classList.remove('hero-fixed')
    heroNav.classList.remove('hero-nav-fixed')
    heroText.classList.remove('h1-fixed')
    heroImg.classList.remove('hero-img-fixed')
  } else {
    hero.classList.add('hero-fixed')
    heroNav.classList.add('hero-nav-fixed')
    heroText.classList.add('h1-fixed')
    heroImg.classList.add('hero-img-fixed')
  }
  if (fromTop > 360) {
    heroNav.classList.add('nav-mobile', 'hidden')
    intro.classList.add('intro-fixed')
    hamburger.classList.remove('hidden')
  } else {
    hamburger.classList.add('hidden')
    heroNav.classList.remove('nav-mobile','hidden')
    intro.classList.remove('intro-fixed')
  }
}

}

It works, but I have to adjust for every screen size I want to support, and it is extremely laggy! It is probably a very wrong way to do it, so could someone help me make it more efficient and less laggy on mobile devices?

My guess is that the constant resizing of the text is one of the problems, as well as the height change of the hero image. I play with position fixed, and padding-top changes in the CSS to compensate the disappearing (becoming fixed positioned) elements.

Could some library, like RxJS help, or is there a VanillaJS elegant solution as well?

Balázs Orbán
  • 559
  • 1
  • 4
  • 26
  • Don't fire it every time the scroll event is triggered. See: https://stackoverflow.com/questions/9144560/jquery-scroll-detect-when-user-stops-scrolling – kuanb Jul 10 '17 at 16:20

1 Answers1

0

To make this more efficient in the Javascript side, you could use something like lodash's debounce.

Changing layout can be a very resource intensive operation so you might want to try leaving the element fixed position all the time and only adjusting its size (and/or the size of its parents) with the CSS transform property. scale() would work quite nicely here.

nemo
  • 334
  • 1
  • 3
  • 10
  • So if I get it right, it delays the function by some milliseconds, and instead of after every scroll event, it only fires if the given amount of time elapsed? is it like [throttleTime](https://www.learnrxjs.io/operators/filtering/throttletime.html) ? – Balázs Orbán Jul 10 '17 at 16:29
  • @BalázsOrbán - Yes, you're correct on your assertion and throttleTime looks like the RxJS equivalent. – nemo Jul 10 '17 at 16:51