Jevgeni Smirnov
Jevgeni Smirnov

Reputation: 3797

Hiding popup if click was made outside. Why my script doesn't work?

I found a solution here, on stackoverflow, the script is following:

jQuery(document).mouseup(function (e){
    var container = jQuery(".quick-info");
    if (container.has(e.target).length === 0) {
        container.hide();
    }
});

Mine try was:

jQuery('body:has(.quick-info:visible):not(.quick-info)').click(function (e) {
    jQuery(".quick-info").hide();
});

So my script means: Catch click which was made on body, but not on .quick-info, and body has .quick-info visible. What might be the problem? May be some wrong selector?

UPDATE 1

Based on Raminson answer.

jQuery('body > *:not(.quick-info)').click(function (e) {    
    var container = jQuery(".quick-info");
    if (container.has(e.target).length === 0 && e.target.nodeName != 'A'){
    jQuery(".quick-info").hide();
    }

});

So with > only single selector chosen.

e.target.nodeName != 'A' is for link , which opens this window. I know, that I could put class or something there.

Upvotes: 1

Views: 840

Answers (3)

Ram
Ram

Reputation: 144679

Try the following:

$(document).on("click", function(e) {
  if (!$(e.target).hasClass("quick-info") && $('.quick-info').is(':visible')) {
     $(".quick-info").hide();
  }
});

DEMO

Upvotes: 0

OptimusCrime
OptimusCrime

Reputation: 14863

I've had sooooo many problems trying to get "click outside"-logic to work. I came over this plugin: http://benalman.com/projects/jquery-outside-events-plugin/ that solved everything for me. You simply bind the event on the element. You could give it a try, even tho I see you have solved your own problem.

Upvotes: 0

Alex Ball
Alex Ball

Reputation: 4474

Or :

jQuery('body:has(.quick-info:visible)').click(function (e){
    if($(e.target).is(".quick-info")) return;
    jQuery(".quick-info").hide();
});

//if($(e.target).hasClass("quick-info")) return;

based on VisioN comment and THIS post hasClass() is to prefer at is()

Upvotes: 0

Related Questions