Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Close modal popup while clicking outside of popup in svelte

Tags:

svelte

I have the popup modal in one of my app.I would like to close this popup while clicking outside of modal.I can achieve this behaviour using javascript but i can't quite find a way to make this work using svelte framework.for now i'm achieving that behaviour like this

if(e.target.classList.contains('my-modal')){
     e.target.style.display="none";
 }

but i would like to have this worked using svelte.

like image 681
rabin prajapati Avatar asked Mar 12 '18 04:03

rabin prajapati


1 Answers

A common way to solve this is to have a background element behind the modal that covers the screen and intercepts click events: https://svelte.technology/repl?version=1.57.1&example=modal-with-slot

This is also a good way to (for example) fade out the background to make the modal more visible.

Another approach is to use the special <:Window> component to listen for clicks, and stop the propagation of any clicks that begin inside the modal: https://svelte.technology/repl?version=1.57.1&gist=ba5f8a78263f2cdfbc16b1ae8732da5d

<:Window on:click='set({ message: "clicked outside the box" })'/>

<div class='clickzone' on:click='event.stopPropagation()'>
  <div class='inner' on:click='set({ message: "clicked inside the box" })'>
    {{message}}
  </div>
</div>
like image 170
Rich Harris Avatar answered Sep 20 '22 07:09

Rich Harris