Modal close if (click mousedown is inside modal & click mouseup is outside)

Hi.

I want to close my modal when user click outside <div class="modal-dialog">.
My code below works wonderfully except if user move his mouse during the click.
If at mousedown the mouse is in modal-dialog but at mouseup the mouse is outside (mouse has moved during the click), than the modal close :frowning:
I would like to prevent this behavior and not close modal if mouse at mousedown is inside modal-dialog. Is it possible ?

I did some search and I have found that

if coords of mousedown and mouseup are not equal, the click event won’t be fired

But it appears to be not true as the click event is fired in my situation. Is this information not correct for Stimulus ?

Thank you for your help !

<div data-controller="modal">
    <button id="btn-user" data-action="modal#open" type="button">WonderfulButton</button>
    <div class="modal" tabindex="-1" data-modal-target="modal" data-action="click->modal#close" data-close-modal>
        <div class="modal-dialog">Content of my modal (form)</div>
    </div>
</div>
import { Controller } from '@hotwired/stimulus';

/**
 * @property {HTMLElement} modalTarget
 */

export default class extends Controller {
    static targets = ['modal']

    open() {
        this.modalTarget.style.display = "flex";
    }

    close(event) {
        if (event.target.hasAttribute("data-close-modal")) {
            this.modalTarget.style.display = "none";
        }
    }
}

Have a look at this component. Packed with knowledge! Thank me later :wink:

1 Like

Thank you for the component @SylarRuby it looks great but I prefer keep it simple. It looks like a huge script just to achieve what I want. Isn’t there a quick fix ?

You can copy the entire file and use as your modal. That’s the way to do it.

What about just using ‘mousedown->modal#close’?

1 Like

Yesss @tleish you are a genius :bulb:
I was not aware that it’s possible to use this event with Stimulus, thank you.

You can use any JavaScript events to trigger stimulus controller functions.

1 Like