Hey This might be weird but I am using code.org as a school thing and my addeventlistener is not working could you help me with this?

<!DOCTYPE html>
<html>
<head> 
  <title>Switch Backround Color</title>
  <link rel="stylesheet" type="text/css" href="style.css">
  </head>
  <body>
    <button>Switch Color</button>
    <script type="text/javascript">
      var color = ["#222f3e","#f368e0","#ee5253","#0abde3","#10ac84",,"#5f27cd"];
      var i = 0;

      document.querySelector("button").addEventListener("click",function(){
        i =  i < color.legnth ? ++i : 0;
      document.querySelector("body").style.background = color[i]
      })
     
    
    
    <link rel="stylesheet" href="style.css">
    
      </script>
  </body>
</html>

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).

I see length mispelt

 color.length

Hey MrBondx! I saw your answer and I did spell it wrong, But I am trying to make it so when I click a button it will change the color of the background. It might just the platform I’m using. If you have any recommendations to help me fix my coding. Just reply back! Thanks.

Once I fix the misspelling, there is the <link rel="stylesheet" href="style.css"> in the middle of the JS section - that can’t be there. If I comment that out, it works for me:

<!DOCTYPE html>
<html>
<head> 
  <title>Switch Backround Color</title>
  <link rel="stylesheet" type="text/css" href="style.css">
  </head>
  <body>
    <button>Switch Color</button>
    <script type="text/javascript">
      var color = ["#222f3e","#f368e0","#ee5253","#0abde3","#10ac84",,"#5f27cd"];
      var i = 0;

      document.querySelector("button").addEventListener("click", function() {
        i = i < color.length ? ++i : 0;
        document.querySelector("body").style.background = color[i]
      })
      
      // <link rel="stylesheet" href="style.css">
    </script>
  </body>
</html>

Thanks! My teacher was very impressed!

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.