Last active
May 15, 2024 05:51
-
-
Save fre-sch/9b913aa272f6b166e1fff6ad6b3a7de1 to your computer and use it in GitHub Desktop.
Svelte 4 single visible menus/popover/tooltip
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script> | |
import Popover from "./popover.svelte" | |
</script> | |
<div> | |
<p> | |
Some text here and show a <Popover label="popover(1)">First popover</Popover> and some more text. | |
</p> | |
<p> | |
Another <Popover label="popover(2)">second popover</Popover> and some more text. | |
</p> | |
<p> | |
Third | |
<Popover label="popover(3)"> | |
<ul> | |
<li>third</li> | |
<li>popover</li> | |
</ul> | |
</Popover> and some more text. | |
</p> | |
</div> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script context="module"> | |
let current | |
function setCurrent(fn) { | |
if (current) { current(); current = null } | |
current = fn | |
} | |
</script> | |
<script> | |
export let label | |
let visible = false | |
function toggleVisible() { | |
(visible = !visible) ? setCurrent(() => visible = false) : setCurrent(null) | |
} | |
</script> | |
<svelte:window on:click={() => setCurrent(null)} /> | |
<div class="popover"> | |
<span class="action" on:click|preventDefault|stopPropagation={toggleVisible}>{label}</span> | |
<div class="popover-content" class:show={visible}> | |
<slot/> | |
</div> | |
</div> | |
<style> | |
.popover { | |
display: inline-block; | |
position: relative; | |
} | |
.popover .action { | |
text-decoration: underline; | |
} | |
.popover-content { | |
background: white; | |
border: 1px solid gray; | |
padding: 0.5rem; | |
border-radius: 0.2rem; | |
box-shadow: 0px 3px 10px rgba(0, 0, 0, 0.3); | |
display: none; | |
position: absolute; | |
width: 200px; | |
top: 100%; | |
left: 0; | |
z-index: 1000; | |
} | |
.popover-content.show { | |
display: initial; | |
} | |
</style> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment