문제

I'm using jquery .mouseup() to close a popop when a user clicks outside of it. My issue is this only works the first time it's used. I've tried the .on() version but that doesn't help.

$(document).ready(function() {
    $(document).mouseup( function(e) {
      var container = $("#mpop-loop");
      if (container.has(e.target).length === 0) {
        container.fadeOut("fast").remove();
      }
    });
});

and

$(document).ready(function() {
    $(document).on("mouseup", function(e) {
      var container = $("#mpop-loop");
      if (container.has(e.target).length === 0) {
        container.fadeOut("fast").remove();
      }
    });
});

How can I make this work everytime it's triggered?

도움이 되었습니까?

해결책

.has only works on descendants, ignoring the element itself. Try this (you don't need $(document).ready since you're binding the event to the document anyway):

    $(document).on("mouseup", function(e) {
      var container = $("#mpop-loop");
      if (!container.has(e.target).length && !container.is(e.target)) {
        container.fadeOut("fast");
      }
    });

http://jsfiddle.net/mblase75/bWDXH/

다른 팁

$('body').click(function(){

    $("#mpop-loop").fadeOut("fast");

});

If you remove "#mpop-loop" then the event might have to be added again when you open the container again.

Could you try using the delegation of the "on" function and use the ":not(.popup-class)" filter to delegate the click event to all elements on the page other than the popup? Just a thought so that the popup being clicked wont trigger a close as well.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top