The piece of code below sucessfully manages to change the position of a block within a grid when you click on it ( on the grid ).
However , I intend to do it when I press on a key. It happens that when I change the EventListener from "click" to "keydown" I get no response if I press on any key of my laptop while running the script.
I assume something is wrong with the element (I need to focus it? How ?) , or the document somehow is unable to recognize the key input. What can I do to try fix this problem ?
let x = 5;
let y = 5;
function CreateSnake(){
tabuleiro.appendChild(snake);
snake.style.gridColumnStart = x;
snake.style.gridRowStart = y;
snake.classList.add("snake");
};
tabuleiro.addEventListener("click" , function(){
moveSnakeRight();
remove()
});
function moveSnakeRight(){
if ( x < 10)
console.log(x++)
;
}
function remove(){
snake.remove()
}
My guess is that you've got the
keydownevent listener on the wrong element. In order to handle thekeydownevent, the element must be able to receive focus (settingtabindex). See the following demo: https://jsfiddle.net/mqe59dL6/An alternative is to handle the event on the
documentinstead. Trydocument.addEventListener("keydown", ...).