Seydina's avatar

How can we disable body scrolling when a modal is displayed in Alpine JS?

I want to know if there is a way of disabling body scrolling when my Alpine modal is shown? This is possible in React with hook and in Vanilla JS but in Alpine I don't know how to achieve it.

1 like
4 replies
s4muel's avatar
s4muel
Best Answer
Level 50

here is what an A.I. suggests:

In Alpine.js, you can disable body scrolling when a modal is open by toggling a class on the body element. Here’s an example of how you can do it:

function modal() {
    return {
        open: false,
        openModal() {
            this.open = true;
            document.body.style.overflow = 'hidden';
        },
        closeModal() {
            this.open = false;
            document.body.style.overflow = 'auto';
        }
    }
}

In this example, openModal and closeModal are methods that are called when the modal is opened and closed, respectively. When the modal is opened, the openModal method sets the overflow style of the body to ‘hidden’, which disables scrolling. When the modal is closed, the closeModal method sets the overflow style of the body back to ‘auto’, which re-enables scrolling.

<div x-data="modal()">
    <button @click="openModal()">Open Modal</button>
    <div x-show="open" @click.away="closeModal()">
        <!-- Modal content -->
    </div>
</div>

In this example, clicking the button calls the openModal method and opens the modal. Clicking outside the modal calls the closeModal method and closes the modal. While the modal is open, scrolling on the body is disabled. When the modal is closed, scrolling is re-enabled. This should give you the behavior you’re looking for.

Seydina's avatar

@Snapey in this case how to put it on that modal :

@props(['title'])
<div x-data="{show : false}" x-show="show" x-on:open-modal.window="show = true" x-on:close-modal.window="show = false"
    class="fixed inset-0 z-50">

    <!-- Gray background -->
    <div class="fixed inset-0 dark:bg-slate-700/40">
    
        <!-- Modal body -->

        <div id="wads-modal" class="mt-10 bg-white rounded-md m-auto inset-0 max-w-5xl max-h-[520px]">

            <div class="flex items-center justify-between border-b border-gray-300">
                @if (isset($title))
                <div class="text-gray-800 text-lg font-bold px-6 py-4">
                    {{$title}}
                </div>
                @endif
                <button class="text-gray-600 hover:text-gray-800 px-6 py-4 focus:outline-none"
                    x-on:click="$dispatch('close-modal')"><span class="material-icons-outlined">
                        close
                    </span></button>
            </div>

                <livewire:events-wizard />

        </div>

    </div>

</div>

Please or to participate in this conversation.