1

Can someone suggest me the Javascript cross-browser(should support IE 11 and new versions of Safari, Firefox, Chrome) equivalent for the JQuery's event.originalEvent property? I tried directly using event.originalEvent in my JS code, which is working perfectly fine on Chrome Browser, but not on Firefox.

I need this property to differentiate between an actual mouse click and programmatic click on an element, and I don't have the freedom to use JQuery.

EDIT: The answer here seems to be doing the trick. Thanks everyone for helping out.

2 Answers2

3

That's just the native event. Check its isTrusted property:

The isTrusted read-only property of the Event interface is a boolean that is true when the event was generated by a user action, and false when the event was created or modified by a script or dispatched via dispatchEvent.

const div = document.querySelector('div');
div.addEventListener('click', (e) => {
  if (e.isTrusted) console.log('manual click');
  else console.log('script click');
});
setInterval(div.click.bind(div), 2000);
<div>click</div>
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
1

In jQuery event, event.originalEvent is equivalent to Event object which is passed to an event listener in javascript.

{
  let jQEvent, vanillaEvent;
  $( "input" ).bind( "click", e => console.log( jQEvent = e.originalEvent ) );
  document.querySelector( "input" ).addEventListener( "click", e => console.log( vanillaEvent = e ) );
  
  document.querySelector( "input" ).addEventListener( "click", e => console.log( vanillaEvent === jQEvent ) );

  document.querySelector( "input" ).addEventListener( "click", e => console.log( `Triggered with manual: ${e.isTrusted}` ) );
}

  setTimeout( () => {
    document.querySelector( "input" ).dispatchEvent( (()=>{
      let event = new Event( "click" );
      event.screenX = 1;
      event.screenY = 1;
      return event;
    })() );
  }, 2000 );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="submit">

Don't use that answer. They are mutatable values.

Isitea
  • 741
  • 5
  • 13
  • If that's the case then directly checking the 'e' object should say whether click was programmatic or manual. But e is always populated either ways. – Roshan P Shajan Apr 25 '18 at 06:31
  • @RoshanPShajan use `.isTrusted` for checking that. If `.isTrusted` is true, that event was triggered with a manual click. – Isitea Apr 25 '18 at 06:36
  • @RoshanPShajan Don't use that answer. They(properties) are mutatable. I add a snippet to mutate them. – Isitea Apr 25 '18 at 07:24