2021年1月7日星期四

jQuery - Run function when clicking outside element

In this code I can open the .options menu when I click the .select element however because I use e.stopPropagation(); on the input option to allow the menu to close, I need to incorporate e.target so that if it isn't the target, the menu will close (allowing for click outside).

How do I use e.target to hide the .options menu when clicking away or if I click .select a second time?

$(".select").each(function(e) {    var $this = $(this),      options = $this.find(".options");      $this.click(function(e) {      $(".options").attr("hidden", "hidden");      options.attr("hidden") ?        options.removeAttr("hidden") :        options.attr("hidden", "hidden");    });    options.find("input").click(function(e) {      e.stopPropagation();      $(".options").attr("hidden", "hidden");    });  });
.select {    border: 1px solid #dedede;    border-radius: 6px;    margin: 1.3rem 0;    width: 250px;    min-height: 40px;    box-sizing: border-box;    overflow: hidden;    cursor: pointer  }    .selected {    display: flex;    padding: 10px;  }    .options {    display: flex;    flex-direction: column  }    .options[hidden] {    display: none;    flex-direction: column;    width: 250px;  }    .options input {    display: none;  }    .options label {    transition: all 0.2s ease-out;    padding: 10px;  }    .options label:hover {    background-color: #f5f5f5;  }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>  <div class="select">    <div class='selected'>      <div class="selected__text">Click Me</div>    </div>    <div class="options" hidden="hidden">      <label>        <input type="radio" value="First">Click to Close      </label>      <label>        <input type="radio" value="Second">Click to Close      </label>    </div>  </div>
https://stackoverflow.com/questions/65622585/jquery-run-function-when-clicking-outside-element January 08, 2021 at 10:24AM

没有评论:

发表评论