Small web component to determine if clicks occur inside or outside a panel.
The normal way: npm install --save svelte-panel-click
As a Svelte component (see the demo here):
<SveltePanelClick
on:clickExternal="set({ lastClick: 'outside' })"
on:clickInternal="set({ lastClick: 'inside' })"
>
<p class="inside-the-panel">
Click anywhere inside this box to trigger an internal click, or
outside the box to trigger an external click.
</p>
</SveltePanelClick>
{#if lastClick}
<p>You last clicked {lastClick}.</p>
{/if}
<script>
import SveltePanelClick from '[email protected]'
export default {
components: {
SveltePanelClick
}
}
</script>
<style>
p.inside-the-panel {
border: 1px solid black;
padding: 15px;
}
</style>
Any time any click event happens within the DOM window
, this
component emits one of two events:
clickInternal
- When the click event happens inside the
component element.clickExternal
- When the click event happens outside the
component element.This component might be used for a modal popup that is hidden when click events outside the modal happen (see the demo):
<p>This text is not inside the panel.</p>
<p>If you click the button, it will reveal the panel.</p>
<PanelClick
on:clickExternal="externalClickHandler(event)"
on:clickInternal="internalClickHandler(event)"
>
{#if visible}
<div class="panel">
<p>This text is inside the panel.</p>
<p>
If you click the button or outside the panel it
will hide, but if you click elsewhere inside the
panel, it won't hide.
</p>
<button on:click="set({ visible: false })">
Hide the Panel
</button>
</div>
{/if}
</PanelClick>
<button
ref:button
on:click="set({ visible: true })"
>
Show the Panel
</button>
<script>
import PanelClick from '[email protected]'
export default {
components: { PanelClick },
methods: {
externalClickHandler(event) {
if (event.target !== this.refs.button) {
// the click was *not* on the "Show Panel" button
this.set({ visible: false })
}
},
internalClickHandler(event) {
// the click happened inside the panel
}
}
}
</script>
<style>
div.panel {
border: 1px solid black;
padding: 15px;
}
</style>
Published and released under the Very Open License.