A simple, small (565 bytes) and easy to use function to detect if the user clicks outside an element.
npm install vanilla-click-outside
<head>
<link rel="stylesheet" href="./path/to/vanilla-click-outside.umd.css" />
<script defer src="./path/to/vanilla-click-outside.umd.js"></script>
</head>
<body>
<div id="target">
<section></section>
</div>
</body>
JavaScript:
const target = document.getElementById('target')
vanillaClickOutside(target, (type, event) => {
console.log(type, event)
})
import { vanillaClickOutside } from 'vanilla-click-outside'
const target = document.getElementById('target')
vanillaClickOutside(target, (type, event) => {
console.log(type, event)
})
Option | Default | Type | Description |
---|---|---|---|
removeListener |
true |
boolean | If you want to handle removeEventListener by yourself. |