Detect if focus event was triggered by user/browser or jQuery

时光毁灭记忆、已成空白 提交于 2021-01-27 08:38:10

问题


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.

  • How to detect if focus event was triggered by user (not programmatically)?

回答1:


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>


来源:https://stackoverflow.com/questions/46726814/detect-if-focus-event-was-triggered-by-user-browser-or-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!