jQuery click event - How to tell if mouse was clicked or enter key was pressed?

自古美人都是妖i 提交于 2019-12-01 05:22:34

Here's the solution I came up with, it's surprisingly simple. I trapped keydown on the tab links, and triggered the click event when keyCode was 13. Luckily, the trigger function allows us to pass extra parameters to the event handler...

$("#tabs li a").keydown(function(e) {
  if(e.keyCode == 13) {
    $(this).trigger("click", true);
    e.preventDefault();
  }
});

So I just had to change my click handler to receive the new parameter and use it...

$("#tabs li a").click(function(e, enterKeyPressed) {
  if(enterKeyPressed)
    alert("Enter key");
  else
    alert("Clicked");
});

I put up a demo on jsFiddle as well. Thanks to everyone who read the question.

Would a global "focus" variable work, which disable focus on mouse setting after tab usage on a given tab until a mouse is moved to a new block.

This would not be the feature your requesting, but I believe it might give you what your looking for.

eg. mouse hoovers option 5, you hit tab, now you store the 5 in the variable, disallowing focus to 5 until something else been focused on, but as soon something else is focused, global is turned back to -1.

Not cleanest workaround I admit that freely.

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