DeveloperBreeze

Tutorials Programming Tutorials, Guides & Best Practices

Explore 149+ expertly crafted tutorials tutorials, components, and code examples. Stay productive and build faster with proven implementation strategies and design patterns from DeveloperBreeze.

Managing Modals with Livewire and JavaScript

Tutorial August 14, 2024
javascript php

Add a script to listen for the custom events emitted by Livewire and open the modals accordingly.

<script>
    document.addEventListener('DOMContentLoaded', function () {
        // Listen for the custom 'open-modal' event
        window.addEventListener('open-modal', event => {
            const modalId = event.detail.modalId;
            const modalElement = document.getElementById(modalId);
            if (modalElement) {
                modalElement.classList.remove('hidden');
            }
        });

        // Close modal logic
        document.querySelectorAll('[data-modal-hide]').forEach(button => {
            button.addEventListener('click', function () {
                const modalId = this.getAttribute('data-modal-hide');
                const modalElement = document.getElementById(modalId);
                if (modalElement) {
                    modalElement.classList.add('hidden');
                }
            });
        });
    });
</script>