Click event outside an element in js

by November 16, 2015 0 comments
You can hook up to the click event of document and then make sure #menucontainer is not an ancestor of the clicked element (jQuery.closest()).
If it is not, then the clicked element is outside of the #menucontainer and you can safely hide it.
$(document).click(function(event) { 
    if(!$(event.target).closest('#menucontainer').length) {
        if($('#menucontainer').is(":visible")) {
            $('#menucontainer').hide()
        }
    }        
})
Hope it helps.

An Nguyen

Developer

Sharing daily exciting lesson learned and posts about .NET, SQL Server, HTML, Javascript - jQuery, CSS - Bootstrap, SalesForce CRM, Kentico CMS and so on.

0 comments :

Post a Comment