Skip to content
This repository has been archived by the owner on Oct 15, 2023. It is now read-only.

A simple easy to use script to determine whenever the user clicks outside a selected element.

License

Notifications You must be signed in to change notification settings

muuvmuuv/vanilla-click-outside

Repository files navigation

VanillaClickOutside 🍦

Demo

A simple, small (790 bytes) and easy to use function to detect if the user clicks outside an element.

Installation

npm install vanilla-click-outside

You can also use the new ESM import syntax to directly use this lib in your browser without installing it via a package manager.

How to use

You can follow the below instructions or look into ./docs/index.html.

HTML

<head>
  <script defer src="./path/to/vanilla-click-outside.umd.js"></script>
  <!-- OR -->
  <script
    defer
    src="https://unpkg.com/vanilla-click-outside/dist/vanilla-click-outside.umd.js"
  ></script>
</head>
<body>
  <div id="target">
    <section></section>
  </div>
</body>

Browser (IIFE)

const target = document.getElementById('target')
vanillaClickOutside(target, (type, event) => {
  console.log(type, event)
})

JavaScript (ESM)

import vanillaClickOutside from 'vanilla-click-outside'

const target = document.getElementById('target')
vanillaClickOutside(target, (type, event) => {
  console.log(type, event)
})

Browser (ESM)

<script type="module">
  import vanillaClickOutside from './path/to/vanilla-click-outside.modern.js'
  // OR
  import vanillaClickOutside from 'https://unpkg.com/vanilla-click-outside/dist/vanilla-click-outside.modern.js'

  vanillaClickOutside(target, (type, event) => {
    console.log(type, event)
  })
</script>

Options

Option Default Type Description
removeListener true boolean If you want to handle removeEventListener by yourself.