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.
$('button'). click(function(event, wasTriggered) { if (wasTriggered) { alert('triggered in code'); } else { alert('triggered by mouse'); } }); $('button').
To check if event is triggered by a human with JavaScript, we can use the isTrusted property. to check if the event is triggered by a human in our event handler callback. e is the event object and it had the isTrusted property. If isTrusted is true , then the event is triggered by a human.
How to trigger focus event on a textbox using javascript? For example in jQuery we can trigger the focus event with $('#textBox'). focus() .
The focus event occurs when an element gets focus (when selected by a mouse click or by "tab-navigating" to it). The focus() method triggers the focus event, or attaches a function to run when a focus event occurs.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With