Detect click inside/outside of element with single event handler

后端 未结 10 1726
南笙
南笙 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条回答
  •  甜味超标
    2020-12-04 16:14

    Using jQuery, and assuming that you have

    :

    jQuery(function($){
      $('#foo').click(function(e){
        console.log( 'clicked on div' );
        e.stopPropagation(); // Prevent bubbling
      });
      $('body').click(function(e){
        console.log( 'clicked outside of div' );
      });
    });
    

    Edit: For a single handler:

    jQuery(function($){
      $('body').click(function(e){
        var clickedOn = $(e.target);
        if (clickedOn.parents().andSelf().is('#foo')){
          console.log( "Clicked on", clickedOn[0], "inside the div" );
        }else{
          console.log( "Clicked outside the div" );
      });
    });
    

提交回复
热议问题