5

I want to know if the focus event is triggered programtically or by human ?

I am writing the part of the script

    jQuery( document ).on( 'focus', '#song_artist_focus', function(event) {
                if(event.originalEvent === undefined ){
                 alert('I am not human');
                 return;}
                alert('I am human') ;
           });

                            

And when i call this script programtically like this

jQuery('#song_artist_focus').focus();

It still shows that event is triggred by human. Please help ?

UPDATE

I checked this solution Check if event is triggered by a human. But doesn't work on focus events.

Community
  • 1
  • 1
beginner
  • 2,366
  • 4
  • 29
  • 53
  • 2
    Possible duplicate of [Check if event is triggered by a human](https://stackoverflow.com/questions/6692031/check-if-event-is-triggered-by-a-human) – Vivek Doshi Jun 18 '17 at 14:37
  • Too fast to "mark as Duplicate" @VivekDoshi – beginner Jun 18 '17 at 14:41
  • Its working please try again , and given answer is same as in the above question – Vivek Doshi Jun 18 '17 at 14:48
  • @VivekDoshi Sorry man, This is embarrassing. It is working now. But when i checked it, It didn't work. maybe i was doing something wrong. But i am using adeneo's solution in my script That looks better. thanks :) – beginner Jun 18 '17 at 15:01
  • I was also able to give the first answer , but it was already given in other question , no issue , you got your answer , that matters. :) – Vivek Doshi Jun 18 '17 at 15:03

2 Answers2

3

Your problem is that the focus event doesn't bubble.
jQuery fixes that with a little magic to make it more like the other events, but it still doesn't quite work like an event that naturally bubbles.
To fix the problem, use the focusin event instead, as it bubbles, and do .trigger('focusin')

jQuery(document).on('focusin', '#song_artist_focus', function(event) {
  if (event.originalEvent === undefined) {
    console.log('I am not human');
  } else {
    console.log('I am human');
  }
});


jQuery('#song_artist_focus').trigger('focusin');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="song_artist_focus">
adeneo
  • 312,895
  • 29
  • 395
  • 388
2

Html :

<input type='text' id='try' >try
<button id='click'>Click</button>

jQuery :

$("#try").focus(function(event) {
    if (event.originalEvent === undefined) {
        console.log('not human')
    } else {
        console.log(' human');
    }
});

$('#click').click(function(event) {
    jQuery('#try').focus();
});

Try it , you will get expected result.

Vivek Doshi
  • 56,649
  • 12
  • 110
  • 122