I am trying to create a block of code which invokes a function when any key is pressed.
my abysmal code
<!doctype html>
<html>
<body>
<canvas style="background-color:red;" id="redcanvas">
</canvas>
<script>
function(e) {
document.addEventListener("keydown", function(e)).getEelementById("redcanvas").style = "background- color:black;"
}
</script>
</body>
</html>
I have been looking up how to do it for hours, but I can’t quite figure it out. I see a lot of issues with my code, but don’t know how to solve them as I am VERY new to coding.
I’ve tried looking up multiple credible websites such as w3schools and this website, stack overflow, but I don’t know what the issue is, and therefore don’t know how to solve it. I expected that when a "keydown" event was initiated on the html document it would get the id of the canvas and change its background color. It did not work.
2
Answers
Here’s what I changed:
The
addEventListener
is directly attached to thedocument
object. This listens for keydown events throughout the entire document.The function inside
addEventListener
is correctly declared now.The
getElementById
method is used to select the canvas element with the ID "redcanvas". Then, thestyle.backgroundColor
property is changed to "black". This is more specific than using the style property directly.The syntax for adding an event listener in this manner is
document.addEventListener(name, listener)
. You don’t need to wrap this in its own function, because you want the listener to be added (even though it’s not run) as soon as the page loads, not after some function is called.To define an anonymous function using the function keyword (there are other ways), you use the syntax
function(args) {...}
, with the function body between the curly braces.To get the
redcanvas
element, you need to call thegetElementById()
function as a method ofdocument
(document.getElementById()
), not onfunction
.