Svelte – UseDirective

0 min read


Alright guysss.. welcome back to our channel.. kali ini sangat menarik ya materi yang akan kita bahas hahaha

click_outside.js

export function clickOutside(node) {
	const handleClick = (event) => {
		if (!node.contains(event.target)) {
			node.dispatchEvent(new CustomEvent("outclick"));
		}
	};

	document.addEventListener("click", handleClick, true);

	return {
		destroy() {
			document.removeEventListener("click", handleClick, true);
		}
	};
}

dan kemudian kita buat file ClickOutside.svelte

<script>
	import { clickOutside } from "./source/click_outside";

	let showModal = true;
</script>

<button on:click={() => (showModal = true)} style="margin-top: 100px">Show Modal</button>
{#if showModal}
	<div class="box" use:clickOutside on:outclick={() => (showModal = false)}>
		Click outside me!
	</div>
{/if}

<style>
	.box {
		--width: 100px;
		--height: 100px;
		position: relative;
		width: var(--width);
		height: var(--height);
		left: calc(50% - var(--width) / 2);
		top: calc(50% - var(--height) / 2);
		display: flex;
		align-items: center;
		padding: 8px;
		border-radius: 4px;
		background-color: #ff3e00;
		color: #fff;
		text-align: center;
		font-weight: bold;
	}
</style>

dan import ke App.svelte

	<Scatterplot />
	<CustomTransition />
	<ClickOutside />

dan hasilnya akan seperti ini …

okay sudah berhasil ya… link github ada disini… see you on next time ….

Bima Sena

Leave a Reply

Your email address will not be published. Required fields are marked *