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

TL;DR

To disable scrolling on everything except the modal div in Webflow, you can achieve this by using custom code and manipulating the CSS properties. Here's a step-by-step guide on how to do it:

Step 1: Add a custom attribute to the body element

In your Webflow project, open the page settings and add a custom attribute to the body element. You can name it something like "data-modal-open". This attribute will be used to toggle the scrolling state.

Step 2: Create a new class for the modal div

In the Webflow Designer, create a new class for your modal div. Let's call it "modal".

Step 3: Add custom code

Go to the page settings, and under the "Custom Code" tab, add the following code:

```javascript

<script>

    var modal = document.querySelector('.modal'); // Get the modal element

    var body = document.querySelector('body'); // Get the body element

    function toggleModalScroll() {

        body.classList.toggle('no-scroll'); // Toggle the 'no-scroll' class on the body element

    }

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

        toggleModalScroll();

    });

</script>

```

Step 4: Add custom CSS

Next, go to the page settings, and under the "Custom Code" tab, add the following CSS:

```css

<style>

    .no-scroll {

        overflow: hidden !important; // Hide the scrollbar and prevent scrolling

    }

</style>

```

Step 5: Apply the new class to the modal div

In the Webflow Designer, apply the "modal" class to your modal div.

That's it! Now, when the modal is triggered, the custom code will add the "no-scroll" class to the body element, preventing scrolling on everything except the modal div. When the modal is closed, the "no-scroll" class will be removed, and scrolling will be enabled again.

Please note that this solution assumes you have a single modal on your page. If you have multiple modals, you may need to modify the custom code to handle each modal separately.

Rate this answer

Other Webflow Questions