Reputation: 3599
I'm trying to detect if focus event was triggered by user (manually).
When it comes to the click
event, it is possible to check if event.originalEvent
is present inside handler method:
typeof event.originalEvent != "undefined"
Unfortunately, it behaves different for focus event. Please check the example.
Try to click on the first <input>
and then click on "trigger click" button for the second input, you will see click undefined
, what means that the event.originalEvent
is not present.
Then try to click on the first <input>
followed by the click on "trigger focus" button for the second input, you will see focus object
, event.originalEvent
is present this time.
Upvotes: 6
Views: 2469
Reputation: 43481
Apply mousedown
event to check if it's user action or not:
$(document).ready(function() {
var isUserClick = false;
$("input").mousedown(function() {
isUserClick = true;
});
$("input").on("click focus blur", function(event) {
console.log(event.type, typeof event.originalEvent, isUserClick ? 'user' : 'script');
setTimeout(function() {
isUserClick = false;
}, 200);
});
$("button").click(function() {
$("input." + $(this).attr("class")).trigger($(this).data("event"));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
FIRST:
<input class="first" />
<button class="first" data-event="click">trigger click</button>
<button class="first" data-event="focus">trigger focus</button>
<button class="first" data-event="blur">trigger blur</button>
<br>
<br> SECOND:
<input class="second" />
<button class="second" data-event="click">trigger click</button>
<button class="second" data-event="focus">trigger focus</button>
<button class="second" data-event="blur">trigger blur</button>
<br>
Upvotes: 5