Search code examples
javascriptinternet-explorerdom-eventskeycode

How to get a e.keycode?


I have a code:

var mainMenuContainer = document.getElementById('main-menu-container');
var mainMenuLinks = mainMenuContainer.getElementsByTagName('a');

function myFunction(links, i) {
    return function () {
        console.log(links[i]);
    }
}

for (var i = 0; i < mainMenuLinks.length; i++) {
    mainMenuLinks[i].onkeydown = myFunction(mainMenuLinks, i);
}

I can now get the link where the key press occurred. I still need to get the e.keycode of key that was pressed on the link. How to do it?
(I need to use old methods to support browsers, so the code is like this).


Solution

  • To not edit your myFunction, you could wrap the call:

    for (var i = 0; i < mainMenuLinks.length; i++) {
        var onKeyDownFunc = myFunction(mainMenuLinks, i);
        mainMenuLinks[i].onkeydown = function(e) {
           console.log(e.keycode);
           onKeyDownFunc();
        };
    }