小能豆

How do I detect a click outside an element?

javascript

I have some HTML menus, which I show completely when a user clicks on the head of these menus. I would like to hide these elements when the user clicks outside the menus’ area.

Is something like this possible with jQuery?

$("#menuscontainer").clickOutsideThisElement(function() {
    // Hide the menus
});

阅读 158

收藏
2023-12-25

共1个答案

小能豆

Yes, you can achieve this functionality in jQuery by attaching a click event to the document and checking whether the clicked element is within the specified container or its descendants. If the click is outside the container, you can then hide the menus. Here’s a simple example:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Click Outside Example</title>
  <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
  <style>
    #menuscontainer {
      border: 1px solid #ccc;
      padding: 10px;
      margin: 20px;
    }
    .menu {
      display: none;
      margin-top: 10px;
      padding: 5px;
      background-color: #f0f0f0;
    }
  </style>
</head>
<body>

<div id="menuscontainer">
  <div class="menu" id="menu1">Menu 1</div>
  <div class="menu" id="menu2">Menu 2</div>
</div>

<script>
$(document).on("click", function(event) {
  var container = $("#menuscontainer");

  // Check if the clicked element is not a descendant of the container
  if (!container.is(event.target) && container.has(event.target).length === 0) {
    // Hide the menus
    $(".menu").hide();
  }
});

$(".menu").on("click", function(event) {
  // Prevent the click from reaching the document
  event.stopPropagation();
});

$("#menuscontainer").on("click", function() {
  // Toggle the visibility of menus when the container is clicked
  $(".menu").toggle();
});
</script>

</body>
</html>

In this example:

  • The menus are initially hidden (display: none;).
  • Clicking on the #menuscontainer toggles the visibility of the menus.
  • The $(document).on("click", ...) event checks if the click is outside the container and hides the menus accordingly.
  • The .menu click event prevents the click from reaching the document, stopping the propagation.

Make sure to adjust the CSS selectors and structure based on your actual HTML and CSS.

2023-12-25