Search code examples
javascriptjquerymouseevent

e.target is body on click when context menu is visible


I have this event:

$(document).on('click', function(e) {
   var $target = $(e.target);
   if ($target.is('.element')) {
      console.log('element');
   }
});

And I have this issue:

When I right click to show context menu and then click on .element (when context menu is visible) the e.target is body not .element in Chrome.

How can I detect if I click on .element?


Solution

  • I've resolve the issue by adding this code:

    function inside(element, x, y) {
        var offset = element.offset();
        var width = element.outerWidth();
        var height = element.outerHeight();
        return (x > offset.left && y > offset.top &&
                x < (offset.left + width) && y < (offset.top + height));
    }
    
    $(document).on('click', function(e) {
       e = e.originalEvent;
       var inside_elements = $('.element').get().filter(function(element) {
           return inside(element, e.pageX, e.pageY);
       });
       if (inside_elements.length) {
          console.log('element');
       }
    });
    

    EDIT: and found another solution using this:

    $(document).on('click', function(e) {
       e = e.originalEvent;
       var node = document.elementFromPoint(e.pageX, e.pageY);
       var $target = $(node);
       if ($target.is('.element')) {
          console.log('element');
       }
    });
    

    EDIT2 weird enough this don't happen when I've try to recreate the issue in codepen, maybe it's something with focus/blur of textarea on click.