PROJET AUTOBLOG


Warrior du Dimanche

Site original : Warrior du Dimanche

⇐ retour index

How can I listen for a click outside of an element in JavaScript? - 30 seconds of code

mercredi 8 novembre 2023 à 09:48

Pour écouter un click hors d'un élément, on utilise l'event delegation: on vérifie si la target de l'event correspond ou pas à l'objet qu'on veut.

  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
<link rel="stylesheet" href="http://www.warriordudimanche.net/./plugins/Galart/style.css"/> <link rel="stylesheet" href="http://www.warriordudimanche.net/./plugins/Galart/assets/lightbox.css"/> <script src="http://www.warriordudimanche.net/./plugins/Galart/assets/lightbox.js"> <script>[].forEach.call(document.querySelectorAll("[lightbox]"), function(el) { el.lightbox = new Lightbox(el);});

► Commentaires