Made with
by Alex Iglesias.

Disable scrolling on click

There are some times when you need to prevent the user from scrolling when a certain event occurs. An example could be when a modal is opened after clicking a button.

Get the code

This is just some dummy text so you can scroll through the page.

How to use it

It is as simple as copying the custom code and pasting it in the before </body> tag  of your page/project.
After that, you just need to place the following custom attributes to your trigger elements:

  • scroll="disable" for those elements that must disable scrolling when clicked.
  • scroll="enable" for those elements that must enable scrolling when clicked.
  • scroll="both" for those elements that must disable scrolling on first click and re-enable scrolling on second click. If you are not planning to use this feature, just delete it from the code.

Note: to add a custom attribute in Webflow, go to the Element Settings and in the custom attributes section add Name=scroll | Value=action with no quotes (" ").

It is recommended to set your modal container overflow property to auto in order to guarantee scrollability inside it when the content is larger than the viewport.

If you don't want to use attributes, you can modify the code to target classes or ID's.

<!-- Disable Scroll Script -->
<script>
var Webflow = Webflow || [];
Webflow.push(function () {
    var $body = $(document.body);
    var scrollPosition = 0;

    $('[scroll="disable"]').on('click', function () {
        var oldWidth = $body.innerWidth();
        scrollPosition = window.pageYOffset;
        $body.css('overflow', 'hidden');
        $body.css('position', 'fixed');
        $body.css('top', `-${scrollPosition}px`);
        $body.width(oldWidth);
    });
    $('[scroll="enable"]').on('click', function () {
        if ($body.css('overflow') != 'hidden') { scrollPosition = window.pageYOffset; }
        $body.css('overflow', '');
        $body.css('position', '');
        $body.css('top', '');
        $body.width('');
        $(window).scrollTop(scrollPosition);
    });
    $('[scroll="both"]').on('click', function () {
        if ($body.css('overflow') !== 'hidden') {
            var oldWidth = $body.innerWidth();
            scrollPosition = window.pageYOffset;
            $body.css('overflow', 'hidden');
            $body.css('position', 'fixed');
            $body.css('top', `-${scrollPosition}px`);
            $body.width(oldWidth);
        } else {
            $body.css('overflow', '');
            $body.css('position', '');
            $body.css('top', '');
            $body.width('');
            $(window).scrollTop(scrollPosition);
        }
    });
});
</script>
Copy to clipboard