0

I was working on some simple code and I keep getting an error for "Cannot read property 'classlist' of null" even though I had defined it earlier. I have been messing around for like 20 mins to try to see if it was a syntax error, but as far as I know, it isn't.

JS:

var charater = document.getElementById("charater")
var block = document.getElementById("block");
function jump() {
    charater.classList.add("animate"); //error here
    setTimeout(function(){
        charater.classList.remove("animate");
    }, 1000);
}

HTML:

<!doctype html>
<html lang="en" >
<head>
<meta charset="UTF-8">
<title>Game_test</title>
<link href="GameTest_1_css.css" rel="stylesheet" type="text/css">
</head>
<script src="Unnamed Site 2/gametstjs1.js"></script>
<body onclick="jump()">
<div id="game">
  <div id="charater"></div>
  <div id="block"></div>
</div>
</body>
</html>

CSS (if needed):

@charset "UTF-8";
body {
    
    margin: 0;
    padding: 0;
}
#game {
    height: 200px;
    width: 500px;
    border: 3px solid
}
#charater {
    width: 20px;
    height: 50px;
    background-color:#085E19;
    position: relative;
    top: 150px;
    animation: jump 500ms;
    }
#block {
    width: 20px;
    height: 20px;
    background-color:#424343;
    position: relative;
    top:130px;
    left:480px;
    animation: block 3.75s infinite linear;
}
@keyframes block{
    0%{left: 480px;}
    100%{left: -40px;}
}
@keyframes jump{
    0%{top:150px;}
    30%{top:100px;}
    60%{top:100px;}
    100%{top:150px;}
}

As always thanks for any help :)

Trevor
  • 13
  • 2
  • Welcome to Stack Overflow! The **only** reason `getElementById` returns `null` is if there is no element with that `id` in the DOM as of when you call it. Your `script` element is earlier than the elements it refers to, so they don't exist as of when it runs. Move it to the end of the document, just prior to the closing `

    ` tag, or add `defer` to it, or make it a module (modern browsers only) by adding `type="module"` to it (modules are automatically deferred).

    – T.J. Crowder Feb 28 '21 at 09:46

0 Answers0