开发者

jquery if an element is not clicked

开发者 https://www.devze.com 2023-03-11 18:59 出处:网络
Is there an efficient way in jQuery to detect if anything other than a specific element (and it\'s children) has been clicked ??

Is there an efficient way in jQuery to detect if anything other than a specific element (and it's children) has been clicked ??

<body&g开发者_运维知识库t;
  <header></header>
  <p>stuff<p>
  <div class="floating-form">
    <form>more stuff</form>
  </div>
  <footer></footer>
</body>

Whats the best way to remove the floating form, by listening for a click on anything other than the floating form?


  1. Bind a click event listener to $(document) that removes div.floating-form.
  2. Bind a click event to div.floating-form that stops event propogation.


The usual approach is to assign a click event handler to the specific element that does nothing other than stop event propagation. Then assign another click handler to the entire page (i.e. to the document) that removes the element in question. Clicks on the element won't propagate up to the document, so you'll get the functionality you want.


You can use the event.target attribute to determine what element triggered the click.

http://api.jquery.com/event.target/


$(document).click(function() {
    //do something
});
$(".floating-form").click(function() {
    return false;
});
0

精彩评论

暂无评论...
验证码 换一张
取 消