How to remove / reload locomotive scroll on window resize?

I have a website I’m building that uses a horizontal layout on desktop and switches back to a native vertical layout on smaller screens. I’m using locomotive scroll, which is working great, but I can’t seem to get the window resizing down.

Here is the function for large screens

 const lscroll = new LocomotiveScroll({
    el: document.querySelector('[data-scroll-container]'),
    smooth: true,
    direction: 'horizontal'
});

and on window.resize events, if the width goes below the mobile threshold, I tried to just destroy it and call it again, but with a direction of “vertical” instead of “horizontal”.

 const lscroll = new LocomotiveScroll({
   el: document.querySelector('[data-scroll-container]'),
   smooth: true,
   direction: 'vertical'
 });
 lscroll.destroy();
 lscroll.init();

Any ideas?

Answer

I’ve never used LocomotiveScroll, but it’s a strange example code you provided.

You assign vertical LS to lscroll, then you destroy it (vertical LS) and then init again.

You might want to use something like:

let lscroll = new LocomotiveScroll(...);

const handleResize = () => {
  const desiredType = ... // 'horizontal' or 'vertical'
  if (lscroll.direction !=== desiredType) {
    lscroll.destroy()
    lscroll = new LocomotiveScroll(...);
  }
}

Leave a Reply

Your email address will not be published. Required fields are marked *