Is there an updated method or script that can prevent body scrolling while a modal window is active in Webflow?

TL;DR
  • Add the provided script in Webflow's Custom Code settings under Before </body> Tag to toggle body overflow property for modals.
  • Ensure all modal-related elements have correct class names in both code and design.
  • Publish the site to verify modal functionality and consult with your team for adjustments if needed.

To prevent body scrolling while a modal window is active in Webflow, follow these updated steps and use the appropriate method.

1. Use Custom Code in Custom Code Settings

  • Go to Project Settings in your Webflow dashboard.
  • Navigate to the Custom Code section.
  • Paste this script inside the Before </body> Tag area to toggle the overflow property:

<script>
  document.addEventListener('DOMContentLoaded', function () {
    const openModal = document.querySelector('.open-modal');
    const closeModal = document.querySelector('.close-modal');
    const modal = document.querySelector('.modal'); // Change this selector based on your modal
    const body = document.body;

    openModal.addEventListener('click', function() {
      modal.style.display = 'block';
      body.style.overflow = 'hidden';
    });

    closeModal.addEventListener('click', function() {
      modal.style.display = 'none';
      body.style.overflow = 'auto';
    });
  });
</script>

2. Add Custom Classes to Elements

  • Ensure your modal has a class name, such as .modal. Update the JavaScript code if your class name differs.
  • Add a class to buttons or links that open/close the modal like .open-modal and .close-modal.

3. Verify Modal Functionality

  • Publish your site to test it.
  • Click the element linked to .open-modal to see the modal and check that body scrolling is disabled.
  • Ensure clicking the element linked to .close-modal restores the body scrolling.

4. Collaborate with Designer or Developer

  • If changes are needed, consult with your team’s designer or developer to tweak selectors or handle additional modals.

Summary

In your Webflow site, add the provided script under the Before </body> Tag section in Project Settings. It toggles the body’s overflow property to prevent scrolling when a modal is active and restores it upon closing the modal. Ensure all selectors in your script match those in your design for smooth operation.

Rate this answer

Other Webflow Questions