< Back to Coding, jQuery

Hide an element when clicking outside of it

From http://stackoverflow.com/questions/1403615/use-jquery-to-hide-a-div-when-the-user-clicks-outside-of-it

I used this for hiding a mobile navigation when tapping outside of it:

$(document).mouseup(function (e)
    var container = $("YOUR CONTAINER SELECTOR");

    if (!container.is(e.target) // if the target of the click isn't the container...
        && container.has(e.target).length === 0) // ... nor a descendant of the container

View the demo

Download the demo

Leave a Reply

Your email address will not be published. Required fields are marked *