So far I tried to locate all event listeners based on This post but it did not work:
getEventListeners(Element);
and
'Chrome Developer tools > Elements > Event listeners'
The reason for asking this is:
I'm building the 2D breakout game using pure JavaScript based on the tutorial from Mozilla and managed to enhance it with various features and multiple levels.
I have a set of added event listeners and also a function that removes them, so far everything works fine.
I do not have an event listener for keycode 13(which is the enter key)
The problem is that if I press the Enter key while the animation is ongoing on the canvas, it changes the behavior with increasing the speed of the ball after each keypress and ultimately it renders a different drawing.
If I don't press the Enter key everything works as intended.
The only event listener that increases the speed is a 'click' event, but that is removed immediately after the function is executed, and it shouldn't interfere with the game.
The other problem is that through the above-mentioned methods there are no event listeners found, not even the ones I added myself, albeit they still work.
I could not find anything that relates to that unwanted behavior and I would like to ask if there are other ways to view the active event listeners.
Here is the code I'm working on
[EDIT:
After realising that the bug was coming from a keydown
event, adding preventDefault()
solved the problem.
However, I'm not sure why did this behaviour occur when there was no e.keyCode == 13
setup in the first place and why did the preventDefault()
method solve the issue.
]
It seems that the bug lays in the keydown
event handler (keyDownHandler
). This is what was causing the unexpected behaviour.
The bug disappeared after adding e.preventDefault();
to keyDownHandler
function.
Original:
function keyDownHandler(e) { //on key down
e.keyCode == 37 ? leftPressed = true : null;
e.keyCode == 39 ? rightPressed = true : null;
}
After:
function keyDownHandler(e) { //on key down
e.preventDefault();
e.keyCode == 37 ? leftPressed = true : null;
e.keyCode == 39 ? rightPressed = true : null;
End result: Nothing happens when pressing the Enter Key
Credit to @Joe Fitzsimmons for pointing me in the right direction