Search code examples
javascriptbootstrap-modal

How to make own custom modal events


I am making my very own modal. But I need to have the events for my modal just like the events of modal in bootstrap. Because I want something to happen once my own modal has been shown to the users

My question is what is the equivalent of these bootstrap modal event into plain vanilla js

show.bs.modal
shown.bs.modal
hide.bs.modal
hidden.bs.modal


Solution

  • You can use JavaScript Events for that. Hope the below example helps.

    When the show_modal function calls it will trigger the modal_show event.

    When the hide_modal function calls it will trigger the modal_hide event.

    We can listen both events in anywhere like window.addEventListener('modal_show'...

    function show_modal() {
        // show modal logic here
        
        // Create a custom event
        const event = new Event('modal_show');
        // Dispatch the event
        window.dispatchEvent(event);
    }
    
    function hide_modal() {
        // hide modal logic here
    
        // Create a custom event
        const event = new Event('modal_hide');
        // Dispatch the event
        window.dispatchEvent(event);
    }
    
    // Listen for the event.
    window.addEventListener('modal_show', function (e) { /* ... */ }, false);
    window.addEventListener('modal_hide', function (e) { /* ... */ }, false);