简体   繁体   中英

How to check if the focus event is triggered programmatically

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.

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"> 

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM