I'm trying to write a super sort Javascript library for myself just to make making canvas games slightly easier.
I'd like to add the event listener for the keypresses from Javascript instead of putting it in as an attribute.
But every time I do it it never works properly and I'm getting really frustrated and wasting all my spares trying to figure it out when I could be doing schoolwork!
Anyway do you think somebody could tell me where I'm going wrong? For this code I'd like for it to alert() with which arrow key was just pressed
Here's index.html
<html>
<head>
<script src="spencersjslibrary.js"></script>
</head>
<body>
<div id="blueblock" style="background:blue; width:100px; height:100px;"></div>
<script>addkeylisten("blueblock")</script>
</body>
</html>
And here's spencersjslibrary.js
//Keyboard stuff for moving and yeah
//Adding event listener
function addkeylisten(ida) {
alert(ida)
var ide = document.getElementById(ida)
ide.addEventListener("keypress", keycheck(event))
}
//checking what key was pressed and assign string value to "lastkey"
function keycheck(event) {
var bttn = (event.keyCode);
switch (bttn) {
case 38:
lastkey = "up";
break;
case 40:
lastkey = "down";
break;
case 37:
lastkey = "left";
break;
case 39:
lastkey = "right";
alert(lastkey)
}
}
So I fixed the addEventListener and got it too work fine with a click event but not my keypress one.
Is that just the element type like would it work with a canvas or body element? And if it was like an image or something per-say would it have to be in focus to hear the keypresses?