cluster1
cluster1

Reputation: 5752

JavaScript: Is there a way to detect if an event was triggered by the user (instead of code-triggered)?

I've got this code in which an event is first triggered by the user. Then the event is triggered again within the event-handler.

inputs.forEach(function(item) {

  item.addEventListener('focus', function() {  
    item.parentNode.focus(); 

    setTimeout(function() {
      item.parentNode.blur();
      item.focus();
    }, 1000);
  });  
});

Currently this leads to an infinity recursion.

When I could find a way to detect if the event was triggered by the user then I could check for that. And so avoid the recursion.

Older StackOverflow answers talk about an "originalEvent"-property of the event-object: Detect if a scroll event is triggered manually in jQuery

But this property has always been undefined in my trying.

Therefore: Is there a way how I can check if the event was triggered by the user?

Upvotes: 0

Views: 81

Answers (2)

Csaba Benko
Csaba Benko

Reputation: 1161

You can simply set a flag on the first run.

Then in the beginning of your handler check the state of the flag. If the flag is set already just unset it and return (so the next run will trigger the event again), but not run the remaining part.

If the flag is not yet set, run the remaining part normally, set the flag at the and again.

Upvotes: 0

Suraj
Suraj

Reputation: 3137

Remove

  item.parentNode.focus(); 

Upvotes: 1

Related Questions