Check if event is triggered by a human

Viewed 70371

I have a handler attached to an event and I would like it to execute only if it is triggered by a human, and not by a trigger() method. How do I tell the difference?

For example,

$('.checkbox').change(function(e){
  if (e.isHuman())
  {
    alert ('human');
  }
});

$('.checkbox').trigger('change'); //doesn't alert
9 Answers

More straight forward than above would be:

$('.checkbox').change(function(e){
  if (e.isTrigger)
  {
    alert ('not a human');
  }
});

$('.checkbox').trigger('change'); //doesn't alert

Currently most of browsers support event.isTrusted:

if (e.isTrusted) {
  /* The event is trusted: event was generated by a user action */
} else {
  /* The event is not trusted */
}

From docs:

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 EventTarget.dispatchEvent().

I needed to know if calls to the oninput handler came from the user or from undo/redo since undo/redo leads to input events when the input's value is restored.

  valueInput.oninput = (e) => {
    const value = +valueInput.value
    update(value)
    if (!e.inputType.startsWith("history")) {
      console.log('came from human')
      save(value)
    }
    else {
      console.log('came from history stacks')
    }
  }

It turns out that e.inputType is "historyUndo" on undo and "historyRedo" on redo (see list of possible inputTypes).

Related