Skip to content
Advertisement

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

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();
    }
});

Advertisement

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();
    }
  });
});
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement