How can I disable scrolling on everything except the modal div in Webflow using custom code?

TL;DR
  • Add a modal div with a unique class or ID in Webflow.
  • Insert custom CSS to make the body non-scrollable when the modal is active.
  • Use JavaScript in Page Settings to toggle the 'modal-open' class on the body when opening and closing the modal; replace example class names accordingly.

To disable scrolling on everything except a modal div in Webflow, you can use custom code to manipulate CSS and JavaScript.

1. Set Up Your Modal

  • Add a modal div in your Webflow project. This will be the element that remains scrollable when open.
  • Ensure your modal div has a unique class or ID so it can be targeted specifically.

2. Add Custom CSS

  • Use Embed component to insert custom CSS.
  • Within this component, add styles to make the body element non-scrollable when the modal is active:
  • Add the following CSS:

    ```css

    body.modal-open {

      overflow: hidden;

    }

    ```

3. Implement JavaScript for Toggle

  • Open the Page Settings of the page with your modal.
  • Scroll to the Before </body> tag section and insert the following script to handle the scroll toggle:
  • Add this JavaScript code:

    ```javascript

    document.addEventListener('DOMContentLoaded', function() {

      const modal = document.querySelector('.your-modal-class'); 

      const openModalButton = document.querySelector('.open-modal-button');

      const closeModalButton = document.querySelector('.close-modal-button');

      openModalButton.addEventListener('click', function() {

        modal.style.display = 'block';

        document.body.classList.add('modal-open');

      });

      closeModalButton.addEventListener('click', function() {

        modal.style.display = 'none';

        document.body.classList.remove('modal-open');

      });

    });

    ```

  • Replace .your-modal-class.open-modal-button, and .close-modal-button with the actual class or ID names used in your project.

Summary

To prevent scrolling across the page when a modal div is open in Webflow, apply a combination of custom CSS and JavaScript. The CSS disables body overflow, while the JavaScript toggles a class on the body element to activate or deactivate scrolling based on modal visibility. Ensure you use the appropriate class names from your project in both CSS and JS.

Rate this answer

Other Webflow Questions