Victor
Victor

Reputation: 5353

Jquery capture tab + some key combination

How can I catch, for example, tab+t combination with jQuery? I've found a lot of examples with alt, shift and ctrl, since event object contains special flags in order to understand if, for example, alt was pressed. But there is not such thing for tab.

Upvotes: 0

Views: 460

Answers (2)

Frayt
Frayt

Reputation: 1223

This should work. It's a bit convoluted and there is likely an easier way, but it works fine.

JSFiddle: https://jsfiddle.net/spybhhxc/

var tabdown = false;
var tdown = false;

$(document).keydown(function(e) {
    if(e.which == 9) {
        tabdown = true;
    }
    if(e.which === 84)
    {
        tdown = true;
    }
    if(tabdown && tdown)
    {
        //do your thing
    }
});

$(document).keyup(function(e) {
    if(e.which == 9) {
        tabdown = false;
    }
    if(e.which === 84)
    {
        tdown = false;
    }
});

This presents a problem though, as once you press tab, the document is unfocused as the tab key navigates to elements in a browser. You would be much better off using something like alt or ctrl which don't interact with the browser.

Upvotes: 1

Ramanathan Muthuraman
Ramanathan Muthuraman

Reputation: 752

We can have a tab key pressed [tabPressed] variable which will be set to true on key down and unset the same on its key up event. We will using the tab key pressed[tabPressed] variable to check whether it is in pressed state during the other key press activities. The tab keycode is 9.

jsfiddle link http://jsfiddle.net/e3Lveyj2/

 var tabPressed=false;
 function handleKeyDown(e) {
 var evt = (e==null ? event:e);
 if(evt.keyCode == 9){
    tabPressed=true;
}
 if ((tabPressed) && (evt.keyCode == 84))  { 
    alert ("You pressed 'Tab+t'")
}
}



function handleKeyUp(e) {
 var evt = (e==null ? event:e);

 if(evt.keyCode == 9){
    tabPressed=false;
}
}
document.onkeydown = handleKeyDown;
document.onkeyup = handleKeyUp;

Upvotes: 0

Related Questions