最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - determine focus event: click or tabstop - Stack Overflow

programmeradmin1浏览0评论

How to determine the focus event on jQuery if the focus is fired on click event or tabstop? I have this focus event that if the focus is fired by a tabstop I will execute something and if it is a click I will not execute it.

Here's a pseudo code

$('a').focus(function(){
    if(ThisIsTabStop()) {
         IWillExecuteThis();
    }
});

How to determine the focus event on jQuery if the focus is fired on click event or tabstop? I have this focus event that if the focus is fired by a tabstop I will execute something and if it is a click I will not execute it.

Here's a pseudo code

$('a').focus(function(){
    if(ThisIsTabStop()) {
         IWillExecuteThis();
    }
});
Share Improve this question asked May 27, 2011 at 5:53 rob waminalrob waminal 18.4k18 gold badges52 silver badges65 bronze badges 2
  • 2 I don't have a concrete answer, but one way might be to use the keypress() event to store the time the Tab key was last pressed, and if it was a very short time ago, you can be fairly confident it is a tab stop. Also, to detect a click, bind to the click event. I'm not sure which executes first, but maybe setting a data item on the element in the click handler and checking for that data item in the focus handler would be another way to go. – GregL Commented May 27, 2011 at 5:57
  • The focus event always fires before the click, but mousedown fires before focus. – DarthJDG Commented May 27, 2011 at 8:52
Add a ment  | 

1 Answer 1

Reset to default 10

If an element is clicked, the mousedown event fires before focus. You just need to set a data attribute, and check it in the focus event.

Try this demo: http://jsfiddle/KcGcF/1/

$('a').mousedown(function(e){
    var $this = $(this);

    // Only set the data attribute if it's not already focused, as the
    // focus event wouldn't fire afterwards, leaving the flag set.
    if(!$this.is(':focus')){
        $this.data('mdown',true);
    }
});

$('a').focus(function(e){
    var $this = $(this);
    var mdown = $this.data('mdown');

    // Remove the flag so we don't have it set next time if the user
    // uses the tab key to e back.
    $this.removeData('mdown');

    // Check if the mousedown event fired before the focus
    if(mdown){
        // Click
    } else {
        // Tab
    }
});
发布评论

评论列表(0)

  1. 暂无评论