Checking if div is visible and closing when click outside of it

Tags:



Can somebody explain me how i can combine this two scripts in one? Thanks!

$(document).ready(function(){
    if ($('.myContainer').is(':visible')) {
        alert('Hello');
    } 
});


$(document).mouseup(function(e) 
{
    var container = $(".myContainer");

    if (!container.is(e.target) && container.has(e.target).length === 0) 
    {
        container.hide();
    }
});

Answer

Here’s one way you could combine the two chunks of code you have:

$(document).ready(function(){
  $(document).mouseup(function(e) 
  {
    var container = $(".myContainer");

    if (container.is(':visible') && !container.is(e.target) && container.has(e.target).length === 0) 
    {
        container.hide();
    }
  });
});


Source: stackoverflow