Use jQuery to hide a DIV when the user clicks outside of it

后端 未结 30 3571
庸人自扰
庸人自扰 2020-11-21 04:28

I am using this code:

$(\'body\').click(function() {
   $(\'.form_wrapper\').hide();
});

$(\'.form_wrapper\').click(function(event){
   event.stopPropagatio         


        
30条回答
  •  自闭症患者
    2020-11-21 05:08

    Built off of prc322's awesome answer.

    function hideContainerOnMouseClickOut(selector, callback) {
      var args = Array.prototype.slice.call(arguments); // Save/convert arguments to array since we won't be able to access these within .on()
      $(document).on("mouseup.clickOFF touchend.clickOFF", function (e) {
        var container = $(selector);
    
        if (!container.is(e.target) // if the target of the click isn't the container...
            && container.has(e.target).length === 0) // ... nor a descendant of the container
        {
          container.hide();
          $(document).off("mouseup.clickOFF touchend.clickOFF");
          if (callback) callback.apply(this, args);
        }
      });
    }
    

    This adds a couple things...

    1. Placed within a function with a callback with "unlimited" args
    2. Added a call to jquery's .off() paired with a event namespace to unbind the event from the document once it's been run.
    3. Included touchend for mobile functionality

    I hope this helps someone!

提交回复
热议问题