Скрипт js не выдаёт новый класс с анимацией из css

Изучаю html и css, дошёл до создания подобия динозаврика из Гугла и столкнулся с проблемой: по нажатию на клавишу(по скрипту эта любая кнопка) скрипт вместо того, чтобы выдать класс с анимацией начинает ругаться на некоторые строчки кода. Скрипт у меня через записан сразу в index.html. Сама ошибка:

index.html:23 Uncaught TypeError: Cannot read properties of null (reading 'classList')
at jumpMove (index.html:23)
at HTMLDocument.<anonymous> (index.html:19)

jumpMove @ index.html:23 (anonymous) @ index.html:19

Не понимаю, что не так, далее приведу весь код html, а за ним css:

 <!Doctype html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Не слови Фугас</title>
        <link href="style.css" rel="stylesheet"/>
    </head>
    <body>
        <header>
            <div id="logo">
                <span>Не слови Фугас</span>
            </div>
        </header>
        <script>
        const dino = document.getElementById ("dino");
        const cactus = document.getElementById ("cactus");

        document.addEventListener("keydown", function(event) {
            jumpMove();
        });

        function jumpMove () {
            if (dino.classList != "jumpMove") {
                dino.classList.add("jumpMove")
            }
            setTimeout(function() {
                dino.classList.remove("jumpMove")
            }, 1600)
        }
        </script>
        <div id="block1">
            <h1 onclick="document.location.href = 'index.html'">Анимация</h1>
            <h1 onclick="document.location.href = 'square.html'">по Периметру</h1>
            <h1 onclick="document.location.href = 'game.html'">Игра</h1>
        </div>
        
        <div class="block">
            <div id="dino"></div>
            <div id="cactus"></div>
        </div>
    </body>
</html>

Css:

.head h3 {
    color: #d67b13;
    background-color: yellow;
    height: 70px;
    margin-top: -10px;
}

.block {
    margin-top: 350px;
    border: 1px solid black;
    height: 500px;
    width: 80%;
    margin: auto;
}

body {
    background-color: yellow;
}

#dino {
    background-image:url(img/bat.png);
    background-size: 255px 105px;
    width: 255px;
    height: 105px;
    position: relative;
    top: 200px;
}

#cactus {
    
}


.jumpMove {
    animation: jumpMove 1s linear;
}

@keyframes jumpMove {
    
    0%{
        top: 200px;
        left: 65px;
    }
    
    50%{
        top: 130px;
        left: 65px;
    }
    
    100%{
        top: 200px;
        left: 65px;
    }
}

#keyframes horMove {
    
    0%{
        top: 400px;
        left: 0px;
    }
    
    25%{
        top: 400px;
        left: 820px;
    }

Ответы (1 шт):

Автор решения: Kain

На момент выполнения скрипта html-элемент (который вы пытаетесь получить методом document.getElementById) еще не загружен, так как скрипт стоит раньше элемента. Переместите скрипт ниже, а лучше воспользуйтесь DOMContentLoaded

→ Ссылка