Reputation: 2072
In my code I use jQuery
's click()
function. Is there any way to detect click type? For example the ability to differentiate between mouse clicks and code driven clicks?
Upvotes: 0
Views: 888
Reputation: 74738
Seems to me e.originalEvent
is you need:
$('button').on('click', function (e){
if (e.originalEvent === undefined) {
alert ('triggered by code');
}else {
alert ('triggered by mouse');
}
});
Or may be you would try sending the extra event data to have a check.
Another option is to have a check for e.isTrigger
like:
$('button').on('click', function (e) {
if (e.isTrigger) {
alert ('triggered by code');
}else {
alert ('triggered by mouse');
}
});
Upvotes: 3
Reputation: 167192
When it is clicked physically by mouse, the event
has these properties:
clientX:
clientY:
So, if they are undefined
, it is programmatic.
$(function () {
$("#btn").click(function (e) {
console.log(typeof e.clientX);
if (typeof e.clientX == "number")
alert("Mouse Click");
else
alert("Programmatic");
});
$("#pxy").click(function (e) {
$("#btn").click();
});
});
* {font-family: 'Segoe UI'; font-size: 10pt;}
<script src="https://code.jquery.com/jquery-2.1.4.js"></script>
<input type="button" value="Click" id="btn" />
<input type="button" value="Click the Button" id="pxy" />
Upvotes: 3