3

Say I programmatically set focus on a textarea with a simple document.getElementById('myTextArea').focus();. On that textarea I have an onFocus event:

document.getElementsByName('myTextArea')[0].onFocus = function () {
    alert('I’m focused!');
};

I only want that onFocus to be fired when the user actually focuses on the textarea and not when I set focus programmatically.

Is there a way in the onFocus to tell if the event was triggered by code or by a human, without passing in a parameter of my own?

Brandon Durham
  • 7,096
  • 13
  • 64
  • 101
  • 2
    Why it is so necessary for you to set focus programmatically when you don't want to do that? – bugwheels94 Mar 07 '16 at 20:39
  • @Ankit — This is an oversimplified example for the sake of illustrating my need. – Brandon Durham Mar 07 '16 at 20:50
  • try checking if the hover and focus events are true? Just throwing it out there. – Train Mar 07 '16 at 20:56
  • I believe the answer is no. The only thing I can think of, in your example, is to override the `prototype` for the `focus` function to set some kind of flag on the DOM element that you check in your event handler. Then you know `focus()` was called. – dmeglio Mar 07 '16 at 20:57
  • 1
    Possible duplicate of [Detect synthetic clicks on a webpage](http://stackoverflow.com/questions/27442497/detect-synthetic-clicks-on-a-webpage) – Jeremy J Starcher Mar 07 '16 at 21:53
  • @JeremyJStarcher — That ticket is another case of someone-asked-a-javascript-question-and-got-a-jquery-answer. The questions are definitely the same, though. – Brandon Durham Mar 07 '16 at 22:38
  • @BrandonDurham - That is true, but there is a discussion of regular JavaScript as well. – Jeremy J Starcher Mar 07 '16 at 22:39
  • Agreed. Happy to have this one closed as a dupe. – Brandon Durham Mar 07 '16 at 22:47

1 Answers1

-1

Yes, when is triggered by the browser it produces an 'originalEvent'.