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

Using jQuery Ajax to send data and retrieve responses in the Codeigniter framework

I am struggling with passing values in CodeIgniter and I need some guidance. Could you provide an example code snippet using CodeIgniter to send a value from a view to a controller using Ajax and jQuery, and then display the result on the same page? In my ...

Tips for halting the live graph plotting based on a specific condition with canvas js

I have a piece of code that generates a live graph based on probabilities. I am looking for a way to stop the plotting process as soon as a specific condition is met. <script> window.onload = function () { var dps = []; // dataPoints var c ...

efficiency of a process during ng-repeat execution

Do you see a distinction in how ng-repeat is written in these two examples? <div ng-repeat="item in getItems()"> Versus this: <div ng-repeat="item in items"> Imagine getItems is structured like this: $scope.getItems = function() { return ...

Entering a new row and sending information through ajax

I'm looking for some help with a web page I have that includes a particular table structure: **Check out my Table*:* <table id="staff" class="table"> <thead> <tr> <th>First Name</th> <th>Last Nam ...

When a page with parameters is reloaded, React fails to initiate

I'm encountering an issue with my application in development mode on localhost. When I try to reload the app on a route with parameters, for example: localhost:8080/item/2 React fails to initialize and only a blank page is displayed. However, if I ...

Can an array in html be accessed using a scope variable?

I am facing a challenge with utilizing a Json array in my template file. To access specific elements of the array, I need to use a scope variable. While I can achieve this in the controller, I also require the same functionality in the HTML file. An excer ...

Stubbing out a module's function with Sinon

Let's envision a scenario where there is a file present: // app.js const connection = require('./connection.js') module.exports = function (...args) { return async function (req, res, next) { // code implementation ... const ...

Unable to locate the value property of a null object

I'm currently working on creating a Shopping Cart using HTML, CSS, JavaScript, and JQuery. The idea is that when you click "Add to Cart" for the orange item, most of the HTML elements will disappear, leaving only the table displaying the Shopping Cart ...

Managing multiple Sequelize DB connections in NestJS: A guide

I recently came across the example in the NestJS documentation regarding setting up a Sequelize DB connection. I'm curious about how to connect to multiple databases using Sequelize and TypeScript with NestJS. Can anyone provide guidance on this? ...

What sets npm run apart from npm start?

Our repository contains a substantial amount of TypeScript code that we can compile and execute using "npm run dev." This setup enables us to access the test JavaScript code via localhost. However, when examining the code in the Chrome debugger, approxim ...

Is there a way to figure out the number of days from the current date using jQuery UI datepicker?

Hello there, I'm currently facing an issue with calculating the number of days from the present to a chosen date after utilizing a jQuery datepicker. It seems that the date formatting is getting altered upon selection, causing discrepancies in the ca ...

Hide bootstrap card on smaller screens such as sm and md

Utilizing the Bootstrap 4.1 card component, I showcase categories within the right sidebar - check out a sample image of the card here: Card example image; When viewing on smaller screens, it's preferable to collapse this large card as shown in this ...

Tips for implementing and utilizing an optional parameter within Vue Router

I am trying to set up a route for a specific component that can be accessed in two ways - one with a parameter and one without. I have been looking into optional parameters but haven't found much information. Here is my current route setup: { pa ...

What is the best way to store a range object obtained from getSelection in order to recreate it on a separate page load?

My goal is to develop a web application that enables users to highlight selected text on a webpage with the click of a button. I want these highlights to persist even when the user returns to the page. So far, I have achieved: var selectedRange = documen ...

How to create a loop in Selenium IDE for selecting specific values from a drop-down list?

Is there a way to use Selenium IDE and JavaScript to test a drop-down box with specific items, not all of them, and continuously loop through until the entire list is covered? Any tips or recommendations on how to accomplish this? ...

Each time the Angular children component is reloaded, the user is redirected to localhost:4200

In my Angular project, I encounter an issue with route parameters in children components. While navigating to these child components from the parent is seamless, reloading the child component causes the application to redirect to localhost:4200 and display ...

How can you store JavaScript objects to files, including their methods, in a Node.js environment?

In reading about saving objects to files in Node.js here on Stack Overflow, I understand the process. However, I am curious if there is a method that allows for writing an object in a manner that would enable me to reload the object into memory along wit ...

Highlighting a Table Column with a Radio Button

I am struggling with controlling the highlight of a table using only radio buttons. When I try to change the selector to input:radio, it doesn't work as expected. It seems to only work with the selector provided in my code snippet. $("th").on("clic ...

Group Hover by StyleX

I recently experimented with the innovative StyleX library and encountered a particular challenge. Can a group hover effect be achieved for a component solely using this library? For instance, let's assume we have the following component in Tailwind ...

Importing multiple exports dynamically in Next.js

My current setup involves using a third-party package that I load dynamically in Next.js: const am5 = dynamic(() => import("@amcharts/amcharts5"), {ssr: false}) The imported amcharts5 consists of various exports and imports, such as: export { ...