Menu

gitpiper

onClickOutside javascript Code Snippet in 2024

browsereventintermediate

Last Updated: 21 July 2024

Runs the callback whenever the user clicks outside of the specified element.

  • Use EventTarget.addEventListener() to listen for 'click' events.
  • Use Node.contains() to check if Event.target is a descendant of element and run callback if not.
const onClickOutside = (element, callback) => { document.addEventListener('click', e => { if (!element.contains(e.target)) callback(); }); };
onClickOutside('#my-element', () => console.log('Hello')); // Will log 'Hello' whenever the user clicks outside of #my-element

javascript snippet similar to onClickOutside For You in July 2024

Subscribe to our Newsletter

Subscribe to get resources directly to your inbox. You won't receive any spam! ✌️

© 2024 GitPiper. All rights reserved

Rackpiper Technology Inc

Company

About UsBlogContact

Subscribe to our Newsletter

Subscribe to get resources directly to your inbox. You won't receive any spam! ✌️