1

I cant get tab to work on keydown when control key is down. How can I do this.

     $(document).keydown(function (e) {
        if (e.ctrlKey && e.which === 9){
            alert('tab pressed when controlkey is down');
        }
    });
Anoop
  • 23,044
  • 10
  • 62
  • 76
user1199595
  • 406
  • 2
  • 7
  • 16

1 Answers1

0

here is a working solution. But I wouldn't catch CTRL+Tab if I were you. Most shortcuts like CTRL+S can be caught and then you can you can call event.preventDefault() to prevent the default behavior. In many browsers for example this will stop the dialog box to save the web page from appearing. But with CTRL+Tab it get's caught but event.preventDefault() doesn't have the desired effect, in Firefox CTRL+Tab changes tabs. You can see both in action with the code below. You can take it for a test drive.

<html><body>
<script>

function shortcutHandler(event) {
    if ((event.charCode == 115) && (event.ctrlKey)) {
        document.getElementById("debug").innerHTML += 'CTRL+S<br/>'
        event.preventDefault()
    }
    if ((event.keyCode == 9) && (event.ctrlKey)) {
        document.getElementById("debug").innerHTML += 'CTRL+Tab<br/>'
        event.preventDefault()
    }
}

document.addEventListener("keypress", shortcutHandler, true);
</script>
<div id=debug style="border: 1px solid red"></div>
</body></html>

this is a jquery version, test drive

<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script>

$(window).keypress(function(event){
    if ((event.charCode == 115) && (event.ctrlKey)) {
        document.getElementById("debug").innerHTML += 'CTRL+S<br/>'
        event.preventDefault()
    }
    if ((event.keyCode == 9) && (event.ctrlKey)) {
        document.getElementById("debug").innerHTML += 'CTRL+Tab<br/>'
        event.preventDefault()
    }
});

</script>
</head>
<body>
Press CTRL+S or CTRL+Tab
<div id=debug style="border: 1px solid red"></div>
</body></html>
Marwan Alsabbagh
  • 25,364
  • 9
  • 55
  • 65
  • I tried your link above. It works for me. What browser and OS are you using. I added a jquery version can you check that one – Marwan Alsabbagh Sep 30 '12 at 11:36
  • You're right, it doesn't work in Chrome. I did some research check out https://github.com/jeresig/jquery.hotkeys and http://stackoverflow.com/questions/11000826/ctrls-preventdefault-in-chrome – Marwan Alsabbagh Sep 30 '12 at 11:57
  • yes this code works for control+S $(document).bind('keydown', function (e) { if (e.ctrlKey && (e.which == 83)) { e.preventDefault(); alert('Ctrl+S'); return false; } }); But not for control+tab with keycode 9 – user1199595 Sep 30 '12 at 12:08