Define a focal event: click or tab.

How to detect focus event in jQuery if focus is fired on click or tabstop event? I have this focal event: if the focus is launched by the tabloid, I will do something, and if it is a click, I did not execute it.

Here is the pseudo code

$('a').focus(function(){
    if(ThisIsTabStop()) {
         IWillExecuteThis();
    }
});
+5
source share
1 answer

If an item is clicked, the event mousedownfires before focusing. You just need to set the 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 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
    }
});
+7
source

All Articles