We can see the properties of the object event
associated with it, particularly those that register click coordinates.
If the click was triggered programmatically, they will be zero.
If the click was performed by the user, it will contain the coordinates of the location where the click occurred in relation to the screen.
To do this, we use clientX
and < a href="https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/clientY"> clientY
:
if (e.screenX && e.screenX!=0 && e.screenY && e.screenY!=0) {
// clique real, realizado por um humano ou um robô que usa o rato
}
else {
// clique programático
}
Example
var myButton = document.getElementById("meuBotao");
// se receber clique, debitar para a consola o objeto 'event'
myButton.onclick = function(event) {
console.log(event);
}
// disparar o clique manual (vai ser o primeiro a aparecer na consola)
myButton.click();
<button id="meuBotao">clica-me</button>
jQuery event.isTrigger
With jQuery, as of version 1.7, the framework of the same handles this problem and sets a property on the click event object to flag if the click was performed programmatically:
// Linha #4521 do ficheiro http://code.jquery.com/jquery-1.11.2.js
event.isTrigger = onlyHandlers ? 2 : 3;
There is no official documentation for this property, and in the jQuery forum there is still no definitive answer to the question. subject.
If we look at the source code of jQuery version 1.7 where we first saw this property:
// Linha #3141 do ficheiro http://code.jquery.com/jquery-1.7.js
event.isTrigger = true;
You can see that there are differences, letting you understand that the property is more for the framework's own internal control and may change in future versions.
In short, it can be concluded that we should not consider this property as feasible for the purpose of detecting the origin of the click being preferable a solution in Vanilla JavaScript.
jQuery event.originalEvent
Anyway, we have the object event.originalEvent
that will be set only if the click occurred by a mouse or touch:
$('button').on('click', function (event) {
if (event.originalEvent === undefined) {
// clique programatico
}
else {
// clique rato ou touch
}
});
This object contains what the event
object contains, and is appended only if the event was triggered by mouse or touch .
Let's say it's a copy of the original event because the framework needs to manipulate numerous properties and can do so without disturbing the normal functioning of the objects and properties we're accustomed to in JavaScript: p>
Some events may have specific properties for them. These can be accessed as properties of the object event.originalEvent
.
Quote in the documentation for Event Object
As this object is documented, its use is already advised given some assurance that it will not change suddenly and without warning or portability.