How To Detect A Click Outside An Element In Jquery




Here we consider how to detect a click outside of an element. In Jquery, we can detect a click on an element using Click Event Listener. For example, consider we have a div with id OuterDiv. We can detect a click on this div as follows.

$('#OuterDiv').click(function() {
         $('#OuterDiv').css('color', 'black');
});



Now for detecting a click outside this div, follow these code. Check whether any click inside HTML is from OuterDiv or not?.

$('html').click(function (e) {
        if (e.target.id == 'OuterDiv') {
                $('#OuterDiv').css('color', 'white');
        }
        else
        {
                $('#OuterDiv').css('color', 'red');
        }
});



If the click event is generated from outside the OuterDiv, write inside else part. If the click event is generated from inside the OuterDiv, write inside if part. This code will help you to detect a click outside of an element using Jquery.