Detect click inside/outside of element with single event handler

后端 未结 10 1670
南笙
南笙 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:11

    Here's a one liner that doesn't require jquery using Node.contains:

    // Get arbitrary element with id "my-element"
    var myElementToCheckIfClicksAreInsideOf = document.querySelector('#my-element');
    // Listen for click events on body
    document.body.addEventListener('click', function (event) {
        if (myElementToCheckIfClicksAreInsideOf.contains(event.target)) {
            console.log('clicked inside');
        } else {
            console.log('clicked outside');
        }
    });
    

    If you're wondering about the edge case of checking if the click is on the element itself, Node.contains returns true for the element itself (e.g. element.contains(element) === true) so this snippet should always work.

    Browser support seems to cover pretty much everything according to that MDN page as well.

    0 讨论(0)
  • 2020-12-04 16:12

    This question can be answered with X and Y coordinates and without JQuery:

           var isPointerEventInsideElement = function (event, element) {
                var pos = {
                    x: event.targetTouches ? event.targetTouches[0].pageX : event.pageX,
                    y: event.targetTouches ? event.targetTouches[0].pageY : event.pageY
                };
                var rect = element.getBoundingClientRect();
                return  pos.x < rect.right && pos.x > rect.left && pos.y < rect.bottom && pos.y > rect.top;
            };
    
            document.querySelector('#my-element').addEventListener('click', function (event) {
               console.log(isPointerEventInsideElement(event, document.querySelector('#my-any-child-element')))
            });
    
    0 讨论(0)
  • 2020-12-04 16:13

    In JavaScript (via jQuery):

    $(function() {
      $("body").click(function(e) {
        if (e.target.id == "myDiv" || $(e.target).parents("#myDiv").length) {
          alert("Inside div");
        } else {
          alert("Outside div");
        }
      });
    })
    #myDiv {
      background: #ff0000;
      width: 25vw;
      height: 25vh;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div id="myDiv"></div>

    0 讨论(0)
  • 2020-12-04 16:14

    Using jQuery, and assuming that you have <div id="foo">:

    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" );
      });
    });
    
    0 讨论(0)
提交回复
热议问题