Reputation: 65
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).
Upvotes: 0
Views: 125
Reputation: 177885
You can use code but I would expect a click on a link
I STRONGLY recommend
const mainMenuContainer = document.getElementById("main-menu-container");
const myFunction = (e) => {
e.preventDefault();
if (e.type==="keydown") console.log(e.code);
const tgt = e.target; // or e.target.closest("a") if there are child elements of the link
if (tgt.tagName === "A") {
console.log(tgt.href)
}
};
mainMenuContainer.addEventListener("keydown", myFunction);
mainMenuContainer.addEventListener("click ", myFunction);
<div id="main-menu-container">
<a href="#home">Home</a> | <a href="#about">about</a>
</div>
Upvotes: 1
Reputation: 58
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();
};
}
Upvotes: 0