Question

E.g. I have the following script

<script>
document.onkeydown = function(evt){
        evt = evt || window.event;
        switch (evt.keyCode){
            case 67:
                createNewFile();
                break;
            case 82:
                goToRecords();
                break;
            case 84:
                goToToday();
                break;
            case 36:
                goToMsHome();
                break;
            case 27:
               escToCloseOptions();
                break;
            case 83:
               summary();
                break;  
            case 73:
               insertRecord();
                break;          
        }
    };
</script>

When I press

shift + keycode

to call a function specified, I am just new to JavaScript and I code JavaScript based on other languages I know

Thanks and Regards

Was it helpful?

Solution

Check .shiftKey which returns a boolean indicating if the key is pressed. Placing this conditional around your switch will prevent any events from occurring unless the key is pressed in combination with shift.

document.onkeydown = function(evt){
        evt = evt || window.event;
        if(evt.shiftKey){
        switch (evt.keyCode){
            case 67:
                createNewFile();
                break;
            case 82:
                goToRecords();
                break;
            case 84:
                goToToday();
                break;
            case 36:
                goToMsHome();
                break;
            case 27:
               escToCloseOptions();
                break;
            case 83:
               summary();
                break;  
            case 73:
               insertRecord();
                break;          
        }
      }
    };

OTHER TIPS

You can detect the shift key separately. e.g. if you want to call createNewFile with the shift key down:

if(evt.shiftKey && evt.keyCode == 67) { 
    createNewFile();
}

In your code, you could do something like:

evt = evt || window.event;
switch (evt.keyCode){
    case 67:
        if (evt.shiftkey) {
            // Do something special for shift mode.
        } else {
            createNewFile();
        }
        break;
...
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top