skip to Main Content

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


  1. // Adding event listener to the entire document
    document.addEventListener("keydown", function(e) {
      // Selecting the element by its ID and changing its background color to black
      document.getElementById("redcanvas").style.backgroundColor = "black";
    });
    <!doctype html>
    <html>
      <body>
        <canvas style="background-color:red;" id="redcanvas"></canvas>
      </body>
    </html>

    Here’s what I changed:

    1. The addEventListener is directly attached to the document object. This listens for keydown events throughout the entire document.

    2. The function inside addEventListener is correctly declared now.

    3. The getElementById method is used to select the canvas element with the ID "redcanvas". Then, the style.backgroundColor property is changed to "black". This is more specific than using the style property directly.

    Login or Signup to reply.
  2. 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 the getElementById() function as a method of document (document.getElementById()), not on function.

    <!doctype html>
    
    <html>
    
    <body>
      <canvas style="background-color:red;" id="redcanvas"></canvas>
    
      <script>
        document.addEventListener("keydown", function(e) {
          document.getElementById("redcanvas").style = "background-color:black;"
        })
      </script>
    
    </body>
    
    </html>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search