Skip to content
This repository was archived by the owner on Sep 23, 2021. It is now read-only.

Add ability to use window instead of body for click events #3

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,14 @@ For example, a button that triggers a popup must be excluded. Otherwise, it will

The `ClickOutside` component has an `exclude` prop that expects an array of DOM nodes. Clicks on those nodes or their children will be ignored.

## Scope of higher DOM element

By default, `clickoutside` events will be fired for clicks on the DOM's `body`. If you'd prefer to use `window` as a reference (e.g. so the event is fired when elements beyond the scope of `body` are clicked), add the `useWindow` prop:

```
<ClickOutside on:clickoutside={hidePanel} useWindow>
```

## Example: Show/hide panel

```html
Expand Down
1 change: 1 addition & 0 deletions src/body.svelte
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<svelte:body on:click />
7 changes: 6 additions & 1 deletion src/index.svelte
Original file line number Diff line number Diff line change
@@ -1,11 +1,16 @@
<script>
import { createEventDispatcher } from 'svelte';

import Body from './body.svelte';
import Window from './window.svelte';

export let exclude = [];
export let useWindow = false;

let child;

const dispatch = createEventDispatcher();
const domScope = useWindow ? Window : Body;

function isExcluded(target) {
var parent = target;
Expand All @@ -28,7 +33,7 @@
}
</script>

<svelte:body on:click={onClickOutside} />
<svelte:component this={domScope} on:click={onClickOutside} />
<div bind:this={child}>
<slot></slot>
</div>
1 change: 1 addition & 0 deletions src/window.svelte
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<svelte:window on:click />