universal-click-outside
v1.0.2
Published
Detects clicks outside of any element. Works with JavaScript, Vue, React, Svelte, and more.
Maintainers
Readme
Universal-click-outside
An ultra-lightweight utility to detect clicks outside any element.
Works perfectly with plain JavaScript, Vue, React, Svelte, and any framework that interacts with the DOM.
Ideal for sidebars, dropdowns, modals, interactive menus, and any component that needs to close when a click occurs outside.
🚀 Features
- 🌎 Works with any framework
- 📦 0 Dependencies
- 🧩 Simple and clear API
- 🧘♂️ Supports ignored elements
- 🧼 Includes a
stop()function to remove listeners - ⚡ Super lightweight and zero configuration
🟦 Basic Usage (Vanilla JavaScript)
import { onClickOutside } from "universal-click-outside";
const panel = document.getElementById("panel");
const stop = onClickOutside(panel, () => {
panel.style.display = "none";
});🎯 Usage with Ignored Elements
import { onClickOutside } from "universal-click-outside";
const menu = document.getElementById("menu");
const toggle = document.getElementById("toggle");
onClickOutside(
menu,
() => {
menu.classList.add("hidden");
},
{
ignore: [toggle] // clicks on this element will NOT close the menu
}
);🧹 Cleaning Up Listeners
const stop = onClickOutside(panel, () => {
panel.remove();
});
// When you no longer need it:
stop();🟩 Vue 3 Usage (Real Example)
<template>
<div>
<button ref="btn" @click="open = !open">Open</button>
<div v-show="open" ref="box" class="box">
Content
</div>
</div>
</template>
<script setup>
import { ref, onBeforeUnmount, watch } from "vue";
import { onClickOutside } from "universal-click-outside";
const btn = ref(null);
const box = ref(null);
const open = ref(false);
let stop;
watch(open, (value) => {
if (value) {
stop = onClickOutside(
box.value,
() => {
open.value = false;
stop();
},
{
ignore: [btn.value]
}
);
} else {
stop && stop();
}
});
onBeforeUnmount(() => stop && stop());
</script>📘 API
onClickOutside(target, callback, options?)
| Parameter | Type | Description | |------------------|-----------------|--------------------------------------------------| | target | HTMLElement | Main element | | callback | Function | Triggered when clicking outside | | options.ignore | HTMLElement[] | Elements that should NOT trigger the callback |
Returns
() => void // function to remove listeners