How to prevent body from scrolling when modal window open

Hi everyone,

After trying everyone’s code I found I always had a problem with one of them so I asked ChatGPT to help me write this, it’s based off Sabanna’s original code. It works well on both desktop and iOS, I haven’t tested Android.

You need to add a class to your button that opens your modal called “open-modal” and any button that closes your modal you need to add “close-modal”.

The beginning of the script detects how wide the scrollbar is and then adjusts the padding on the whole website so you don’t get a jump when you open the modal. When you close the modal, this padding gets removed.

I’ve added this to the footer code on the custom code tab in site settings. Make sure you publish your website for this code to work. Bear in mind that it will only work on the published site and not on the preview (the little eye in the designer).

I hope this helps people.

<script>
// create a div with the scroll
let div = document.createElement('div');
div.style.overflowY = 'scroll';
div.style.width = '50px';
div.style.height = '50px';

// Append the div to the document body to get accurate sizes
document.body.appendChild(div);
let scrollWidth = div.offsetWidth - div.clientWidth;

document.body.removeChild(div);

let isIOS = /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;

document.addEventListener('DOMContentLoaded', function() {
  let openModalButtons = document.querySelectorAll('.open-modal');
  let closeModalButtons = document.querySelectorAll('.close-modal');
  let scrollTop = 0;

  openModalButtons.forEach(function(button) {
    button.addEventListener('click', function(e) {
      e.preventDefault();
      if (isIOS) {
        scrollTop = window.pageYOffset;
        document.body.style.position = 'fixed';
        document.body.style.top = `-${scrollTop}px`;
        document.body.style.width = '100%';
      } else {
        document.body.style.overflow = 'hidden';
        document.body.style.paddingRight = scrollWidth + 'px';
      }
    });
  });

  closeModalButtons.forEach(function(button) {
    button.addEventListener('click', function(e) {
      e.preventDefault();
      if (isIOS) {
        document.body.style.position = '';
        document.body.style.top = '';
        document.body.style.width = '';
        window.scrollTo(0, scrollTop);
      } else {
        document.body.style.overflow = 'auto';
        document.body.style.paddingRight = '0px';
      }
    });
  });
});
</script>
2 Likes