willmcpo / body-scroll-lock

Body scroll locking that just works with everything 😏
MIT License
4.04k stars 339 forks source link

Multiple Modals on the same page? #222

Closed minemindmedia closed 3 years ago

minemindmedia commented 3 years ago

Hi, I've finally managed to get this to work properly but I'm wondering how to set this up to work with multiple modal windows on the same page.

For example, I have a mobile menu that opens a modal on every page, then I have other modals that open up forms. I've added 'lock' as a class to use for my modals but it only works for the first modal, my mobile menu and doesn't work for the others.

Here's my script that works on independent modals as long as there aren't two on the same page:

  const scrollTargetElement     = document.querySelector('.lock');
  const disableBodyScrollButton = document.querySelector('.disableBodyScroll');
  const enableBodyScrollButton  = document.querySelector('.lock button');
  const enableBodyScroll        = document.querySelector('body');

  disableBodyScrollButton.onclick = function() {
      console.info('disableBodyScrollButton');
      bodyScrollLock.disableBodyScroll(scrollTargetElement);
  };

  enableBodyScrollButton.onclick = function() {
      console.info('enableBodyScrollButton');
      bodyScrollLock.enableBodyScroll(scrollTargetElement);
  };

  function closePopup(){
    bodyScrollLock.enableBodyScroll(scrollTargetElement);
  }
diachedelic commented 3 years ago

I also ran into this issue, and I ended up making a Vue mixin which hides the overflow of all ancestor elements. Perhaps you can use it as inspiration: https://gist.github.com/diachedelic/b7e9ce7063e87f452d0a5a1ac4ad7a8f

minemindmedia commented 3 years ago

Thanks for the response but I'm not too sure I understand this. It should be a lot more simple to apply this to multiple modal windows imo.

diachedelic commented 3 years ago

I agree. If you find a way please let me know.

minemindmedia commented 3 years ago

@diachedelic - I discovered a different package based on this one which works really well and is easier to setup imo. https://github.com/tuateam/tua-body-scroll-lock

diachedelic commented 3 years ago

Thank you, at some point I will replace my hideous solution with that one (providing it works for me). I'm closing this as it sounds like switching to the other package has solved your issue.