The CSS class fails to run when added in a JS file

I have just started learning CSS and JS, and despite reviewing my code multiple times, consulting w3schools, and searching for similar issues, I am still unable to pinpoint where the error lies.

     <! DOC TYPE HTML>
<html>
<head>
<h1> fruit dodge</h1>
<link rel="stylesheet" href="FDCSS.css">
</head>
<body onkeypress="jump()">
<div id="game">
    
    <div id="player"></div>

In an attempt to resolve the issue, I moved the event to the body element from the html tag, but it did not solve the problem as intended.

CSS:
.animate
{
    animation: jump 500ms;
}
keyframes jump
{
    0%{top: 400px;}
    30%{top: 350px;}
    70%{top: 350px;}
    100%{top: 400px;}
}

I can confirm that the animation itself is functional as I tested it independently before incorporating it into a class.

var player = getElementById("player");
var fruit = getElementById("fruit");

    function jump()
    {
        player.classList.add("animate");
        setTimeout(function()
        {
            player.classList.remove("animate");
        },500);
    }

The purpose of the jump function is to apply the animate class to the player character momentarily and then remove it after the animation duration (500ms).

Answer №1

There seem to be a few mistakes in your code. In the CSS section, make sure to include an @ symbol before keyframes.

Additionally, it is recommended not to animate the top property and instead use hardware accelerated properties like transform. (refer to the example provided below)

.animate {
  animation: jump 500ms;
}

@keyframes jump {
  from {
    transform: translateY(0);
  }
  to {
    transform: translateY(-40px);
  }
}

In the JavaScript part, avoid using global getElementById(), opt for document.getElementById() to select elements.

var player = document.getElementById("player");
var fruit = document.getElementById("fruit");

function jump() {
  player.classList.add("animate");

  setTimeout(function () {
    player.classList.remove("animate");
  }, 500);
}

var player = document.getElementById("player");
var btn = document.getElementById("btn");

function jump() {
  player.classList.add("animate");

  setTimeout(function() {
    player.classList.remove("animate");
  }, 500);
}

btn.addEventListener("click", jump);
.player {
  background-color: #a1887f;
  border-radius: 50%;
  height: 3rem;
  margin: 4rem auto 1rem;
  width: 3rem;
}

button {
  background-color: #c5e1a5;
  border: 2px solid rgba(0, 0, 0, 0.1);
  border-radius: 0.25rem;
  color: rgba(0, 0, 0, 0.6);
  cursor: pointer;
  display: block;
  font-size: 1.25rem;
  margin: auto;
  padding: 0.5rem 1rem;
}

.animate {
  animation: jump 500ms;
}

@keyframes jump {
  from {
    transform: translateY(0);
  }
  to {
    transform: translateY(-40px);
  }
}
<div class="player" id="player"></div>
<button id="btn">Jump</button>

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

How to use puppeteer to extract images from HTML that have alt attributes

<div class="col-lg-4 col-md-4 col-sm-4 col-xs-12 nopadding text-center"><!-- Start Product Photo --><div class="row"><img src="/products/ca/downloads/images/54631.jpg" alt="Product image 1">&l ...

Ways to increase the size of an element within an array using JavaScript

I am currently working on expanding an array in JavaScript. Here is the object below const items = [ { id: 1, name: 'Alice', designs: [ { designId: 1, designName: "designA" ...

In Reactjs, the specified property title is not found within the string type

Currently, I am working with Reactjs and using the nextjs framework. I have encountered an issue while fetching data where I am receiving an error message stating "Property 'title' does not exist on type 'string'". How can I r ...

Passing references between multiple components

I'm currently working on an application using Material-UI in conjunction with styled-components. I am faced with the challenge of passing a ref down to the root <button> node that is created by Material-UI. Material-UI provides a buttonRef prop ...

Inserting a large number of records in MySQL using a batch insertion method

Currently, I am facing an issue with inserting multiple records into a MySQL table at once. Just so you know, I am using Node.js along with MySQL (you can find more information about it here: https://www.npmjs.com/package/mysql) Here is what I have been ...

When attempting to incorporate the "active" class into a Bootstrap 4 carousel using jQuery, issues arise specifically when retrieving data from a MongoDB database

I'm working on a carousel feature where I need to load images from my MongoDB database. However, the issue I'm facing is that even though I've tried adding the active class to the first item, the carousel doesn't transition to display t ...

Is there a way to change a string that says "False" into a Boolean value representing false?

When retrieving values from the backend, I am receiving them as strings 'True' and 'False'. I have been attempting to convert these values into actual Boolean values, however, my current method always returns true. What is the correct a ...

Tips on extracting the value from an observable and storing it in a variable

I am facing a challenge in returning a value from an observable method to assign it to a public variable for later use. Specifically, I need to retrieve this value and store it in the 'viewcount' variable for utilization in another function. pub ...

Retrieve data from a collection by utilizing ng-repeat

I need help implementing a select interface on my website. Users will be able to choose a site, and then the associated country where the site is available will be displayed. To do this, I have a list of sites with information like their names and the co ...

Editing DOM elements within Angular JS using Greasemonkey extension

I have been developing a Greasemonkey script to enhance the performance of a vendor's angularJS tool by automating certain processes. One major obstacle I am encountering is that the element I need to interact with is not yet loaded in the DOM when m ...

Enhance the appearance of your custom Component in React Native by applying styles to Styled Components

I have a JavaScript file named button.js: import React from "react"; import styled from "styled-components"; const StyledButton = styled.TouchableOpacity` border: 1px solid #fff; border-radius: 10px; padding-horizontal: 10px; padding-vertical: 5p ...

Struggling to have images line up side by side within a div

Check out my code snippet here: http://pastebin.com/pDkM4FQi #img1, #img2, #img3, #img4 { display: inline-block; height: 100%; } #navBar { background-color: white; border: 1px solid white; border-radius: 15px; display: inline-block; height ...

The npm command encountered a permission issue when trying to install node-sass

Whenever I run the npm command on my Ubuntu system, I encounter a "permission denied" issue. sudo npm install node-sass EACCES: permission denied, access '/node_modules/node-sass' I have attempted to run the command as a root user or with sudo ...

When using Express.js for file uploading, it is important to first verify that a file has been sent, set a maximum file size limit, and ensure

After working with expressjs for a month, I've encountered some issues with file uploads. Despite researching on Google and various blogs, I haven't been able to find answers to the following three questions: What do I need to do or what setting ...

Tips for displaying JSON data by formatting it into separate div elements for the result object

Having recently started using the Amadeus REST API, I've been making AJAX calls to retrieve data. However, I'm facing a challenge when it comes to representing this data in a specific format and looping through it effectively. function showdataf ...

What are the steps for rearranging a table column?

I am trying to show a text file in a table and allocate some code to each entry. I can display the text file. I can assign the code for each record (though this part is still under development). However, I have encountered an issue. The columns of the t ...

Incorporating the sx attribute into a personalized component

I am currently incorporating MUI v5 along with Gatsby Image in my project. To maintain consistency in my styling syntax throughout the application, I decided to include the sx prop in the GatsbyImage component. This is how I attempted it: <Box compon ...

Can two BootstrapVue tooltips be displayed on a single element with different target settings?

While working in Vue with BootstrapVue, I encountered a problem where the bottom 2 tooltips that I am using both appear on the button targeted by the click to mask this value button. The tooltip containing the SSN is also only appearing on top of the butto ...

Tips for creating a vertical Angular Material slider with CSS

Attempting to modify the angular material directive to render vertically has been a challenge. I experimented with using transform:rotate in the CSS, however, it resulted in the slider behaving and rendering differently. md-slider { position: absolute ...

Why is my MySQL query not returning the most recent results when using setInterval()?

I am currently facing an issue with the setInterval function within the $(document).ready(function(){} My approach involves using setInterval to call a PHP script that executes MySQL queries to check the status of 4 switches and then updating the screen w ...