Alcho holic
Alcho holic

Reputation: 1

How to detect a click on anything other than this one div in jQuery?

I want to hide a div with the class "myProfile" when the user clicks anywhere outside that div. How can I do this?

I have this so far but obviously it says hide the div when the user clicks on it instead of "outside" it:

$('.myProfile').click(function() {
    $(this).hide();
});

Upvotes: 0

Views: 500

Answers (2)

Michael
Michael

Reputation: 2631

Alternatively you could create another div beneath .myProfile that takes up all the space on your page. To the click event of this div you hide both this special layer and your profile view/box. This is a very common way to implement the modal box. This way you don't have to listen on all other elements.

I believe that this is also the way it is done by the popular Lightbox 2 and definitely used in my own very unpopular code hehe.

Upvotes: 2

Pablo Fernandez
Pablo Fernandez

Reputation: 105258

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

  if (!$(event.target).hasClass('myProfile'))
  {
    $(event.target).hide();
  }

});

Upvotes: 3

Related Questions