Detect click inside/outside of element with single event handler

后端 未结 10 1725
南笙
南笙 2020-12-04 15:48

Suppose I have one div in my page. how to detect the user click on div content or outside of div content through JavaScript or JQuery. please help with small code snippet. t

10条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-04 16:04

    Rather than using the jQuery .parents function (as suggested in the accepted answer), it's better to use .closest for this purpose. As explained in the jQuery api docs, .closest checks the element passed and all its parents, whereas .parents just checks the parents. Consequently, this works:

    $(function() {
        $("body").click(function(e) {
            if ($(e.target).closest("#myDiv").length) {
                alert("Clicked inside #myDiv");
            } else { 
                alert("Clicked outside #myDiv");
            }
        });
    })
    

提交回复
热议问题