Skip to content Skip to sidebar Skip to footer

How To Scrolllock Body When A Modal/lightbox Is Open

I am using the lightbox jquery plugin to open a lightbox when a user clicks on a product. Often the lightbox content stretches below the fold, and at the moment the right scrollbar

Solution 1:

Here's a class that'll allow you to do just that:

classScrollLock{
  constructor () {
    this.pageBody = document.querySelector('body');
    this.scrollY = 0;
  }

  saveScrollY = (num) => {
    this.scrollY = num;
  }

  setScrollY = (num) => {
    window.scroll(0, num);
  }

  setScrollOffset = (vOffset) => {
    this.pageBody.style.top = `-${vOffset}px`;
  }

  freezeBodyScroll = () => {
    this.saveScrollY(window.scrollY);
    this.setScrollOffset(this.scrollY);
    this.pageBody.classList.add('is-fixed');
  }

  unfreezeBodyScroll = () => {
    this.pageBody.classList.remove('is-fixed');

    // Don't reset scroll position if lock hasn't occurredif (this.scrollY === 0) return;
    this.setScrollOffset(0);
    this.setScrollY(this.scrollY);
    this.saveScrollY(0);
  }
}

Include the following style declaration:

// In your CSS
body.is-fixed {
  position: fixed;
  max-width: 100%;
}

Use:

const { freezeBodyScroll, unfreezeBodyScroll } = newScrollLock();

// Call when you open your modalfreezeBodyScroll();

// Call when you close your modalunfreezeBodyScroll();

Post a Comment for "How To Scrolllock Body When A Modal/lightbox Is Open"