Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Click source in JavaScript and jQuery, human or automated?

We all know that you can simulate click or any other event on an element using one of these ways:

$('#targetElement').trigger('eventName');
$('#targetElement').click();

I have encountered a situation in which, I should know how an element is clicked. I should know if it's been clicked automatically via code, or by pressing mouse button. Is there anyway I can do it without hacks or workarounds? I mean, is there anything built into browsers' event object, JavaScript, or jQuery that can tell us whether click has been initiated by a human action or by code?

like image 246
Saeed Neamati Avatar asked Aug 08 '11 12:08

Saeed Neamati


1 Answers

Try this:

$('#targetElement').click(function(event, generated) {
    if (generated) {
        // Event was generated by code, not a user click.
    } else {
        // Event was generated by a user click.
    }
});

Then, to make this work, you have to trigger them like this:

$('#targetElement').trigger('click', [true]);

See this jsfiddle.

like image 130
cdhowie Avatar answered Sep 23 '22 07:09

cdhowie