Rahul
Rahul

Reputation: 1

Overriding the default shortcuts of the browser (Ctrl+anyKey)

I am trying to override the default key shortcuts we use in browser (e.g. Ctrl+1, Ctrl+2 to go to Tab1 and Tab2 respectively). I have to do this using JavaScript. Please can anyone help me out?

I tried the below code which works fine when I use alert() but not working perfectly without alert() function.

Code:

<script language="javascript" type="text/javascript">
document.onkeydown = NavigateThrough;
function NavigateThrough (event)
{
    if (!document.getElementById) return;
    if (window.event) event = window.event;
    if (event.ctrlKey)
    {
        var link = null;
        switch (event.keyCode ? event.keyCode : event.which ? event.which : null)
        {
            case 0x31:
                //alert("hi 1 pressed");
                document.getElementById('txt').value = "Number : 1"; 
                break;
            case 0x32:
                //alert("hi 2 pressed");
                document.getElementById('txt').value = "Number : 2"
                break;
            case 0x33:
                //alert("hi 3 pressed");
                document.getElementById('txt').value = "Number : 3"
                break;
        }
    } 
}
</script>
<body >
<input type="text" id="txt">
</body>

Upvotes: 0

Views: 225

Answers (1)

Herrington Darkholme
Herrington Darkholme

Reputation: 6315

try adding event.preventDefault()? because ctrl + 1 will reload the page and interrupt the code.

also, ctrl key is not necessarily enough for cross-platform browser. consider jquery or event.metaKey

jQuery key code for command key

Upvotes: 1

Related Questions