4

With jQuery it's easy. With pure JavaScript isn't, at least it isn't easy to find out how. if (event.clientX && event.clientY) { ... } gives kind-of detection, but it's not 100% accurate.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Aleksandr Makov
  • 2,820
  • 3
  • 37
  • 62
  • Can you describe the situations where it's not accurate? Only real mouse clicks will have those two properties; programmatic clicks should not. – Cᴏʀʏ Apr 23 '13 at 20:38
  • Yes, they should not, but you still *can simulate* it: `new MouseEvent('click').initMouseEvent('click', false, false, null, null, 0, 0, 200, 200,false, false, false, false, 0, document);` Note `200, 200` args. – Aleksandr Makov Apr 23 '13 at 21:01
  • 1
    @AleksandrMakov depends what you want to do. for newer browsers you could think over replacing the `Element.prototype.dispatchEvent` function with your own function that adds a property to the event marking it as simulated event, and then passing the event to the original function. – t.niese Apr 23 '13 at 21:05
  • @t.niese Whoops, sorry, I've started to write my answer before loading your comment. Hope you don't mind. – MaxArt Apr 23 '13 at 21:16

2 Answers2

4

There is a way, but it's quite controversial IMHO. Try this:

HTMLElement.prototype.dispatchEvent = (function(dispev) {
    return function(event) {
        // Do your stuff
        dispev.call(this, event);
    };
})(HTMLElement.prototype.dispatchEvent);

With this, you're able to catch every call to dispatchEvent when a programmatically generated event is dispatched. Of course, this would slow down a bit the dispatching, but shouldn't be a problem unless you're trying to fire a lot of events.

In IE8 you must replace Element.prototype.fireEvent instead, while in IE7 and lower it's just not possible to do anything about it.

MaxArt
  • 22,200
  • 10
  • 82
  • 81
0

Event.isTrusted can be used upto a satisfactory level.

Ashish Singh
  • 1,004
  • 11
  • 23