Categories
Posts

Difference Between A Human Click And A Trigger Click With jQuery

I was recently working on a page that had some existing transitions that happened when a user clicked on an item. My thought was to periodically trigger a click event that would automate the process some what, allowing me to take advantage of the existing transition code.

jQuery has a nifty method called .trigger that takes care of firing the click event for me. Very handy, but then I quickly realized that I needed to be able to tell the difference between a human click event and a .trigger‘d click event.

Fortunately I wasn’t the only one to have run into this issue and there is a solution described at http://stackoverflow.com/questions/6692031/check-if-event-is-triggered-by-a-human/6692173#6692173. The key is event.originalEvent, here is an example from the StackOverflow post:

[sourcecode lang=”javascript”]
$( "#click-me" ).click( function( event ) {
if ( event.originalEvent === undefined ) {
alert( ‘not human’ )
} else {
alert( ‘human’ );
}
} );
[/sourcecode]

You can also try it out on jsFiddle – http://jsfiddle.net/Uf8Wv/

This appears to be specific to jQuery, which in this case wasn’t a big deal since all of the other code on the page was using jQuery as well. The Event object documentation mentions event.originalEvent, but doesn’t indicate that it can be used in this way.