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?
Asked
Active
Viewed 859 times
0

Praveen Kumar Purushothaman
- 164,888
- 24
- 203
- 252

Alex
- 1,982
- 4
- 37
- 70
-
What do you mean by code driven clicks? I know that, but need to know more. – Praveen Kumar Purushothaman Jan 17 '16 at 11:02
-
I mean "code initiated" clicks, like using jQuery's `click` function. I want to distinguish between user's mouse click, and my code's automated clicks. – Alex Jan 17 '16 at 11:04
-
You mean, `.trigger("click")` and `.click()`? – Praveen Kumar Purushothaman Jan 17 '16 at 11:04
-
It's very likely that there would be much cleaner way to do whatever it is you try to do. Like, `$('elem').click( function() { doSomething(true); })` where the parameter to `doSomething` tells if it's a user click, and in code instead of triggering the click call `doSomething(false)`. – JJJ Jan 17 '16 at 11:06
-
1@undroid Tell me if it is working for you. – Praveen Kumar Purushothaman Jan 17 '16 at 11:09
2 Answers
3
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" />

Praveen Kumar Purushothaman
- 164,888
- 24
- 203
- 252
-
cool, also thought about checking if mousemove was updated x time before click or if it was a touch event for other devices – john Smith Jan 17 '16 at 11:11
-
@johnSmith ***Note:** I used `console.dir()` to find stuff.* – Praveen Kumar Purushothaman Jan 17 '16 at 11:11
-
1Thanks @PraveenKumar, good answer. Although your answer meets my requirements, I selected Jai's answer because It is a bit more easier to read. – Alex Jan 17 '16 at 11:51
-
1@undroid Sure... I agree with that too... `:)` Coz that's the right way. – Praveen Kumar Purushothaman Jan 17 '16 at 11:51
3
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');
}
});

Jai
- 74,255
- 12
- 74
- 103