简体   繁体   中英

determine focus event: click or tabstop

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();
    }
});

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.net/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 come back.
    $this.removeData('mdown');

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM