What is the best way to resume a paused animation using JavaScript?

My first game involves triggering an animation that transitions the game screen to greyscale when the character dies. Despite my efforts, I have been unable to successfully trigger this animation using

document.getElementById("object").animationPlayState = "running"
. The CSS code for the game is enclosed within a <div> element in HTML.

To view the full code on Codepen (which currently has some issues), please click on this link: https://codepen.io/flyingchicken22/pen/NWgVrJq

CSS:

#game {
    width: 600px;
    height: 300px;
    border: 2px solid black;
    margin: auto;
    background-image: url("https://t3.ftcdn.net/jpg/01/73/79/26/360_F_173792623_516juhwjkCCZJ9OyesyH7hf7r9zsyH5u.jpg");
    background-size: cover;
    animation: deathAnimation 2s;
    animation-play-state: paused;
}

@keyframes deathAnimation {
    0%{filter:none;}
    100%{filter:grayscale(100%);}
}

Javascript:

var gameLoop = setInterval(() => {
    dead = false
    function rockAnimation() {
        rock.classList.add('rockAnimation')
    }
    const knightTop = parseInt(window.getComputedStyle(knight).getPropertyValue('top'))
    const rockLeft = parseInt(window.getComputedStyle(rock).getPropertyValue('left'))
    if (rockLeft < 0) {
        rock.style.display = 'none'
    } else {
        rock.style.display = ''
    }

    if (rockLeft < 90 && rockLeft > 50 && knightTop > 79) {
        dead = true
    }
    score.innerText++

    const deathAnimation = document.getElementById("deathAnimation")
    const game = document.getElementById("game")
    if (dead == true) {
        clearInterval(gameLoop)
        document.getElementById("youDied").innerHTML = "YOU DIED"
        document.getElementById("playAgain").innerHTML = "Play Again?" 
        game.classList.add(deathAnimation)
        document.getElementById("deathAnimation").style.animationPlayState = "running"
    }
}, 50);

Answer №1

You're attempting to modify an HTML element that doesn't exist. Update

document.getElementById("deathAnimation").style.animationPlayState = "running"
to
document.getElementById("game").style.animationPlayState = "running"

Check out this code snippet:

const background = document.getElementById('game')
const knight = document.getElementById('knight')
const rock = document.getElementById('rock')
const score = document.getElementById('score')
//transfer jump animation functionality to script
function jump() {
    knight.classList.add('jump-animation')
    setTimeout(() => {
        knight.classList.remove('jump-animation')
    }, 500)
}
//Trigger jump animation when any key is pressed
document.addEventListener('keypress', () => {
    if (!knight.classList.contains('jump-animation') && dead == false) {
    jump(); 
    }  
})
//game loop
let dead



var gameLoop = setInterval(() => {
    dead = false
    function rockAnimation() {
        rock.classList.add('rockAnimation')
    }
    const knightTop = parseInt(window.getComputedStyle(knight).getPropertyValue('top'))
    const rockLeft = parseInt(window.getComputedStyle(rock).getPropertyValue('left'))
    if (rockLeft < 0) {
        rock.style.display = 'none'
    } else {
        rock.style.display = ''
    }

    if (rockLeft < 90 && rockLeft > 50 && knightTop > 79) {
        dead = true
    }
    score.innerText++

    const deathAnimation = document.getElementById("deathAnimation")
    const game = document.getElementById("game")
    if (dead == true) {
        clearInterval(gameLoop)
        document.getElementById("youDied").innerHTML = "YOU DIED"
       
game.classList.add(deathAnimation)
        document.getElementById("game").style.animationPlayState = "running"
    }
}, 50);
html {
    background-color: black;
}

#score {
    text-align: center;
    color: rgba(102, 255, 0, 0.993);
}

#game {
    width: 600px;
    height: 300px;
    border: 2px solid black;
    margin: auto;
    background-image: url("https://t3.ftcdn.net/jpg/01/73/79/26/360_F_173792623_516juhwjkCCZJ9OyesyH7hf7r9zsyH5u.jpg");
    background-size: cover;
    animation: deathAnimation 2s;
    animation-play-state: paused;
}

@keyframes deathAnimation {
    0%{filter:none;}
    100%{filter:grayscale(100%);}
}


#knight {
    height: 100px;
    width: 75px;
    position: relative;
    top: 171px;
    left: 50px;
    background-image: url("https://images-wixmp-ed30a86b8c4ca887773594c2.wixmp.com/f/f57b5304-de59-49e3-b0f9-cc29a2458425/dcgy8i3-e6dac283-04a7-40e5-a333-cc645e172df7.png?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ1cm46YXBwOjdlMGQxODg5ODIyNjQzNzNhNWYwZDQxNWVhMGQyNmUwIiwiaXNzIjoidXJuOmFwcDo3ZTBkMTg4OTgyMjY0MzczYTVmMGQ0MTVlYTBkMjZlMCIsIm9iaiI6W1t7InBhdGgiOiJcL2ZcL2Y1N2I1MzA0LWRlNTktNDllMy1iMGY5LWNjMjlhMjQ1ODQyNVwvZGNneThpMy1lNmRhYzI4My0wNGE3LTQwZTUtYTMzMy1jYzY0NWUxNzJkZjcucG5nIn1dXSwiYXVkIjpbInVybjpzZXJ2aWNlOmZpbGUuZG93bmxvYWQiXX0.0LapCzRi5sQjkqzwB5lwWQT_XH1BM4rSMZt7jrflMLk");
    background-size: cover;
}

#rock {
    height: 50px;
    width: 50px;
    position: relative;
    top: 122px;
    left: 550px;
    background-image: url("http://pixelartmaker-data-78746291193.nyc3.digitaloceanspaces.com/image/da268f06e621b21.png");
    background-size: cover;
    animation: rockAnimation 1s linear;
}

@keyframes rockAnimation {
    0%{left: 500px;}
    100%{left: -50px;}
}

.jump-animation {
    animation: jump 0.5s;
}

@keyframes jump {
    0%{top: 171px;}
    50%{top: 70px;}
    75%{top: 70px;}
    100%{top: 171px;}
}

@font-face {
    font-family: VT323;
    src: url(https://fonts.googleapis.com/css2?family=VT323&display=swap);
  }

#gameName {
    text-align: center;
    color: rgba(102, 255, 0, 0.993);
    font-size: 300%;
    font-family: 'VT323';
}

#youDied {
    text-align: center;
    color: rgba(102, 255, 0, 0.993);
    animation: youDied 2s infinite;
}

@keyframes youDied {
    0%{color: rgba(102, 255, 0, 0.993);}
    50%{color: black}
    100%{color: rgba(102, 255, 0, 0.993);}
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div id="game">
        <div id="knight"></div>
        <div id="rock"></div>

    </div>
    
    <h1 id="score">0</h1>
    <h1 id="gameName">KNIGHT HOPPER</h1>
    <h1 id="youDied"></h1>
    <script src="script.js"></script>
</body>
</html>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

My discord.js bot remains silent in response to a user's message, even when no errors are present

My Discord bot is using version 13.1.0 of discord.js and my Node version is 16.7.0. I utilized the commands npm init to generate a package.json file and npm install discord.js to install the Discord package. The code for the bot is written in index.js, an ...

Navigating a roster of users in JavaScript

I'm dealing with a collection of user data stored in an array accountsade: [ { id: 0.4387810413935975, name: "Adrian", password: "345", userName: "nathanael" }, { id: 0. ...

The MVC execution sequence: Controller initialization happening after Ajax call

I'm struggling to understand the execution order in MVC architecture. In my code, I am overriding initialization in the following way: public class HomeController: Controller { protected override void Initialize(RequestContext requestContext) ...

Create static HTML web pages using information from a text file

Exploring a new concept of a random joke generator that loads a unique html page with a quirky joke every time. Currently, the main index page is structured like this: <!DOCTYPE html> <html> <head><title>Jokes</title> ...

Error: "Access-Control-Allow-Origin" header is missing in Firebase Function

I have encountered an issue with my firebase functions GET request. While I am able to receive data using Postman, I am facing difficulties when trying to fetch data from my front-end application. Upon accessing the endpoints, I am seeing the following er ...

Sending information between children components in VueORTransferring data between

So, I have a question regarding the Authentication section of my application. Within my application, I have various components and routes, including register and login. The register functionality is working properly with the API, storing both the usernam ...

Automatically Assigning a Default Value to a Column Using SEQUELIZE ORM

When fetching data from a database using Sequelize ORM, I need to set a default value. Here is an example of the SQL query: SELECT a.affiliate_id, a.active AS current_state, IF(MAX(cn.contract_id) IS NULL ,0, IF(DATEDIFF(NOW(),MAX(cn.contract_date) ...

Adjust the color of the active link on the page using Angular and CSS

I have a project that I need to modify by adding a sub menu that appears on every page but is only coded once. My goal is to highlight the link for the current page, all within one HTML snippet. Although the list renders correctly, I'm struggling to g ...

Using `ng-model` within an Angular directive

Looking to achieve bi-directional binding in an Angular directive Here is my current approach: angular.module('myapp',[]),directive('mydirective', function() { var directive = {}; directive.restrict = 'E'; directi ...

Issue with Chart.js V3.20: Struggling to Filter Legend Labels

Building a dynamic line chart using Chart.js with the capability of up to 19 datasets. The issue arises when there are less than 19 datasets, as the legend still displays for these unused datasets. Previously, a function was used in Chart.js 2.6.0 options ...

utilizing vue model attributes with `${}`

I am encountering an issue with my code. Initially, :src="labels[index]" was working fine for me. However, as my codebase expanded, I needed to use ${app.labels[index]}. Simply using ${app.labels} works, but the addition of [index] causes it to b ...

Unlimited scrolling feature resembling Facebook and Tumblr created using jQuery

Below is the modified code from a tutorial found on hycus.com: <script type="text/javascript> var properlast = 10; $(window).scroll(function() { if($(window).scrollTop() == $(document).height() - $(window).height()) { $("div#load ...

Unable to input any text into the textfield

After implementing redux-form-material-ui for my form, I am facing an issue where I cannot type anything in the textfield. Despite having two textfields and an Autocomplete option, only the Autocomplete box seems to be functioning properly while the textfi ...

Updating certain fields in AngularJS with fresh data

I am facing a challenge with the following code snippet: <div ng-controller="postsController"> <div id = "post_id_{{post.postid}}" class = "post" ng-repeat="post in posts"> ...... <div class="comments"> < ...

Can you explain the purpose of this script? Is it considered harmful?

Today, I received a suspicious phishing email containing the following JavaScript code: <script type="text/javascript" language="Javascript1.1"> <!-- Begin var bCancel = false; function validateRegistrationDetails(form) { hm ...

Monitoring Logfile in Ruby On Rails 3.1

Within my Ruby on Rails application, I have a set of scripts that need to be executed. In order to ensure they are working properly, the application must display and track the content of logfiles generated by these scripts. To provide more context: I util ...

What could be causing the redirection issue in a next.js application?

I recently started working with Next.js and have developed an application using it. On the homepage, I have a timer set for 10 seconds. When the timer hits 0, I want to redirect the user to a feedback page in my "pages" folder. Below is the code I am usin ...

Improving the efficiency of my conditions in a function with Vue JS

Does anyone have any suggestions on how to optimize this function? I feel like it could be shortened to improve its efficiency. Any help or advice would be much appreciated. Function: onStudentActionSelect: function () { if (this.selectedRows.length ...

Issue Detected at a Precise Line Number - Android Studio

Despite my numerous attempts to modify the specific line in question, including leaving it empty, turning it into a comment, or removing it entirely, the error message persists. I even went as far as deleting the class and creating a new one, but the same ...

Pass the identical event to multiple functions in Angular 2

On my homepage, there is a search form with an input box and select dropdown for users to search for other users by location or using html5 geolocation. When a user visits the page for the first time, they are prompted to allow the app to access their loca ...