Saturday, November 28, 2009

How to detect tab key is pressed in javascript?

Recently I was working for a client and they needs plenty of functionality to be implemented in the javascript. And on the way of writing the code, I need to check whether user pressed on the tab key. When user on a particular div and hit the tab key then I need to do some logic. So, is there any event like tab clicked in javascript? NO… So,how to detect it. Below is the code I used for it.

document.onkeydown = keydown;

function keydown(event) {
        var code;
        var e;
        if (document.all) {
            if (!event) {
                var e = window.event;
                code = e.keyCode;
            }
        }
        else if (event.which) {
        code = event.which;
        e = event;
        }
        if (code == 9) {//Write some logic
        }
    }

Note: keycode 9 is for tab key.

Hope this helps you.

2 comments: