javascript - Comment puis-je détecter un clic en dehors d'un élément

Mots clés : javascriptjqueryclickjavascript

meilleur 5 Réponses javascript - Comment puis-je détecter un clic en dehors d'un élément

vote vote

95

$(window).click(function() {   //Hide the menus if visible });  $('#menucontainer').click(function(event){   event.stopPropagation(); }); 
vote vote

87

$(document).click(function(event) {    var $target = $(event.target);   if(!$target.closest('#menucontainer').length &&    $('#menucontainer').is(":visible")) {     $('#menucontainer').hide();   }         }); 
export function hideOnClickOutside(selector) {   const outsideClickListener = (event) => {     const $target = $(event.target);     if (!$target.closest(selector).length && $(selector).is(':visible')) {         $(selector).hide();         removeClickListener();     }   }    const removeClickListener = () => {     document.removeEventListener('click', outsideClickListener)   }    document.addEventListener('click', outsideClickListener) } 
function hideOnClickOutside(element) {     const outsideClickListener = event => {         if (!element.contains(event.target) && isVisible(element)) { // or use: event.target.closest(selector) === null           element.style.display = 'none'           removeClickListener()         }     }      const removeClickListener = () => {         document.removeEventListener('click', outsideClickListener)     }      document.addEventListener('click', outsideClickListener) }  const isVisible = elem => !!elem && !!( elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length ) // source (2018-03-11): https://github.com/jquery/jquery/blob/master/src/css/hiddenVisibleSelectors.js  
      ...       let lastMouseDownX = 0;       let lastMouseDownY = 0;       let lastMouseDownWasOutside = false;        const mouseDownListener = (event: MouseEvent) => {         lastMouseDownX = event.offsetX         lastMouseDownY = event.offsetY         lastMouseDownWasOutside = !$(event.target).closest(element).length       }       document.addEventListener('mousedown', mouseDownListener); 
const outsideClickListener = event => {         const deltaX = event.offsetX - lastMouseDownX         const deltaY = event.offsetY - lastMouseDownY         const distSq = (deltaX * deltaX) + (deltaY * deltaY)         const isDrag = distSq > 3         const isDragException = isDrag && !lastMouseDownWasOutside          if (!element.contains(event.target) && isVisible(element) && !isDragException) { // or use: event.target.closest(selector) === null           element.style.display = 'none'           removeClickListener()           document.removeEventListener('mousedown', mouseDownListener); // Or add this line to removeClickListener()         }     } 
vote vote

76

element.addEventListener('blur', ..., true); //                       use capture: ^^^^ 
$('a').on('click', function () {   $(this.hash).toggleClass('active').focus(); });  $('div').on('focusout', function () {   $(this).removeClass('active'); });
div {   display: none; } .active {   display: block; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a href="#example">Example</a> <div id="example" tabindex="-1">   Lorem ipsum <a href="http://example.com">dolor</a> sit amet. </div>
$('.submenu').on({   focusout: function (e) {     $(this).data('submenuTimer', setTimeout(function () {       $(this).removeClass('submenu--active');     }.bind(this), 0));   },   focusin: function (e) {     clearTimeout($(this).data('submenuTimer'));   } }); 
$('a').on('click', function () {   $(this.hash).toggleClass('active').focus(); });  $('div').on({   focusout: function () {     $(this).data('timer', setTimeout(function () {       $(this).removeClass('active');     }.bind(this), 0));   },   focusin: function () {     clearTimeout($(this).data('timer'));   } });
div {   display: none; } .active {   display: block; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a href="#example">Example</a> <div id="example" tabindex="-1">   Lorem ipsum <a href="http://example.com">dolor</a> sit amet. </div>
$('a').on({   focusout: function () {     $(this.hash).data('timer', setTimeout(function () {       $(this.hash).removeClass('active');     }.bind(this), 0));   },   focusin: function () {     clearTimeout($(this.hash).data('timer'));     } }); 
$('a').on('click', function () {   $(this.hash).toggleClass('active').focus(); });  $('div').on({   focusout: function () {     $(this).data('timer', setTimeout(function () {       $(this).removeClass('active');     }.bind(this), 0));   },   focusin: function () {     clearTimeout($(this).data('timer'));   } });  $('a').on({   focusout: function () {     $(this.hash).data('timer', setTimeout(function () {       $(this.hash).removeClass('active');     }.bind(this), 0));   },   focusin: function () {     clearTimeout($(this.hash).data('timer'));     } });
div {   display: none; } .active {   display: block; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a href="#example">Example</a> <div id="example" tabindex="-1">   Lorem ipsum <a href="http://example.com">dolor</a> sit amet. </div>
keydown: function (e) {   if (e.which === 27) {     $(this).removeClass('active');     e.preventDefault();   } } 
$('a').on('click', function () {   $(this.hash).toggleClass('active').focus(); });  $('div').on({   focusout: function () {     $(this).data('timer', setTimeout(function () {       $(this).removeClass('active');     }.bind(this), 0));   },   focusin: function () {     clearTimeout($(this).data('timer'));   },   keydown: function (e) {     if (e.which === 27) {       $(this).removeClass('active');       e.preventDefault();     }   } });  $('a').on({   focusout: function () {     $(this.hash).data('timer', setTimeout(function () {       $(this.hash).removeClass('active');     }.bind(this), 0));   },   focusin: function () {     clearTimeout($(this.hash).data('timer'));     } });
div {   display: none; } .active {   display: block; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a href="#example">Example</a> <div id="example" tabindex="-1">   Lorem ipsum <a href="http://example.com">dolor</a> sit amet. </div>
click: function (e) {   $(this.hash)     .toggleClass('submenu--active')     .find('a:first')     .focus();   e.preventDefault(); } 
$('.menu__link').on({   click: function (e) {     $(this.hash)       .toggleClass('submenu--active')       .find('a:first')       .focus();     e.preventDefault();   },   focusout: function () {     $(this.hash).data('submenuTimer', setTimeout(function () {       $(this.hash).removeClass('submenu--active');     }.bind(this), 0));   },   focusin: function () {     clearTimeout($(this.hash).data('submenuTimer'));     } });  $('.submenu').on({   focusout: function () {     $(this).data('submenuTimer', setTimeout(function () {       $(this).removeClass('submenu--active');     }.bind(this), 0));   },   focusin: function () {     clearTimeout($(this).data('submenuTimer'));   },   keydown: function (e) {     if (e.which === 27) {       $(this).removeClass('submenu--active');       e.preventDefault();     }   } });
.menu {   list-style: none;   margin: 0;   padding: 0; } .menu:after {   clear: both;   content: '';   display: table; } .menu__item {   float: left;   position: relative; }  .menu__link {   background-color: lightblue;   color: black;   display: block;   padding: 0.5em 1em;   text-decoration: none; } .menu__link:hover, .menu__link:focus {   background-color: black;   color: lightblue; }  .submenu {   border: 1px solid black;   display: none;   left: 0;   list-style: none;   margin: 0;   padding: 0;   position: absolute;   top: 100%; } .submenu--active {   display: block; }  .submenu__item {   width: 150px; }  .submenu__link {   background-color: lightblue;   color: black;   display: block;   padding: 0.5em 1em;   text-decoration: none; }  .submenu__link:hover, .submenu__link:focus {   background-color: black;   color: lightblue; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul class="menu">   <li class="menu__item">     <a class="menu__link" href="#menu-1">Menu 1</a>     <ul class="submenu" id="menu-1" tabindex="-1">       <li class="submenu__item"><a class="submenu__link" href="http://example.com/#1">Example 1</a></li>       <li class="submenu__item"><a class="submenu__link" href="http://example.com/#2">Example 2</a></li>       <li class="submenu__item"><a class="submenu__link" href="http://example.com/#3">Example 3</a></li>       <li class="submenu__item"><a class="submenu__link" href="http://example.com/#4">Example 4</a></li>     </ul>   </li>   <li class="menu__item">     <a  class="menu__link" href="#menu-2">Menu 2</a>     <ul class="submenu" id="menu-2" tabindex="-1">       <li class="submenu__item"><a class="submenu__link" href="http://example.com/#1">Example 1</a></li>       <li class="submenu__item"><a class="submenu__link" href="http://example.com/#2">Example 2</a></li>       <li class="submenu__item"><a class="submenu__link" href="http://example.com/#3">Example 3</a></li>       <li class="submenu__item"><a class="submenu__link" href="http://example.com/#4">Example 4</a></li>     </ul>   </li> </ul> lorem ipsum <a href="http://example.com/">dolor</a> sit amet.
vote vote

69

if(!$(event.target).is('#foo')) {     // hide menu } 
const className = `dropdown-${Date.now()}-${Math.random() * 100}`; 
const onClickOutside = (e) => {   if (!e.target.className.includes(className)) {     show = false;   } }; 
// add when widget loads window.addEventListener("click", onClickOutside); 
// remove listener when destroying the widget window.removeEventListener("click", onClickOutside); 
vote vote

55

$('#menucontainer').click(function(event) {   $('html').one('click',function() {     // Hide the menus   });    event.stopPropagation(); }); 

Questions similaires