What is preventing my Javascript from animating this text to change colors?

Having some trouble getting this color change animation to work on a successful result. I was experimenting with animations for the first time and can't quite pinpoint why it's not functioning as expected. Appreciate any help you can offer!

HTML

<p>Roll two dice and check if they match:</p>
<p id="answerSpace"></p>

CSS

#answerSpace {
  font-size: 52px;
  padding-top: 0px;
  display: block;
  margin: auto;
}

p{
  padding-top: 0px;
  padding-bottom: 0px;
  display: inline-block;
  margin: auto;
}

@keyframes color-change {
  0% { color: red; }
  50% { color: blue; }
  100% { color: red; }
}

Javascript

const randomNum = num => {

let answer = Math.floor(Math.random() * Math.floor(num))

return answer;

};

const compareRolls = () => {

let firstRoll = randomNum(6); console.log("first roll: " + firstRoll);
let secondRoll = randomNum(6); console.log("second roll: " + secondRoll);

if (firstRoll === secondRoll){
a = true; result = "Success!" + ` Two ${firstRoll}s!`}else{  a=false; result ="Nope.";}

console.log(a);

let space = document.getElementById("answerSpace");
if (a == true){space.style.animation = "color-change 1s infinite";}

space.innerHTML = result;

};

compareRolls();

Answer №1

There was a minor issue with your CSS code due to the presence of a semi-colon.

const generateRandomNumber = num => {
    let result = Math.floor(Math.random() * Math.floor(num));
    return result;
};

const compareGeneratedNumbers = () => {
    let firstNum = generateRandomNumber(6); 
    console.log("First number rolled: " + firstNum);
    let secondNum = generateRandomNumber(6); 
    console.log("Second number rolled: " + secondNum);

    if (firstNum === secondNum){
        isMatch = true; 
        outcome = "You got it! Two " + firstNum + "s!";
    } else {  
        isMatch = false; 
        outcome ="Not quite.";
    }

    console.log(isMatch);

    let answerElement = document.getElementById("answerSpace");
    
    if (isMatch == true){
        answerElement.style.animation = "1s ease 0s infinite normal none running color-change";
    }

    answerElement.innerHTML = outcome;

};

compareGeneratedNumbers();
#answerSpace {
    font-size: 52px;
    padding-top: 0px;
    display: block;
    margin: auto;
}

p{
    padding-top: 0px;
    padding-bottom: 0px;
    display: inline-block;
    margin: auto;
   
}

@keyframes color-change {
    0% { color: red; }
    50% { color: blue; }
    100% { color: red; }
}
<p>Roll two dice and see if they match:</p>
<p id="answerSpace"></p>

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

Styling CSS code to centrally align a background image in the footer of a

Within my MVC app, there is a footer displayed on every page that includes an image. I am looking to align the image in the center if possible. The current CSS code for the footer is as shown below: footer { position:absolute; bottom:-150px; /* Th ...

Creating unique validation rules using VeeValidate 3 and vue.js

I have a form where I need to establish specific rules. For instance, consider the following code snippet: <label class="form-label">Price range from</label> <validation-provider rules="required_if:price_to" name="Price range from" ...

Is it possible to incorporate multiple IDs into the changeImage function for a radio

I've encountered an issue with my function that changes images based on radio button selections. It works fine for one image slider, but now I want to make it available for a second slider. The problem is that when I use the radio buttons for the seco ...

Is It Possible to Extract a Hidden Document Value from a Web Browser Using IWebBrowser2 in LabVIEW?

After hours of combing through the internet, I've come up empty-handed in my quest to find information related to my current project. I've created an HTML document that gathers user data and stores it in a JavaScript array. This array is then com ...

Retrieving the value of an inactive HTML checkbox through Request.Form

I am working with an HTML checkbox element: <input type="checkbox" name="MyChkBox" .. /> Using JQuery, I am enabling or disabling this checkbox based on another control: $(this).attr("disabled", "true"); When handling the form data on the server ...

Modifying an HTML list item to become 'active' in a navigation bar

One way I've been implementing my navbar on each page is by using the following code at the bottom of the page within script tags: $("#navbar-partial").load("navbar.html). The code for the navbar list looks like this: <ul id="main-nav" class="nav ...

Encountering a hydration issue in Next.js when attempting to refresh the page after switching languages (excluding English) with next-translate/useTranslation

I've encountered an issue with the useTranslation hook from the next-translate package in my Next.js project. Although all languages are being recognized, I'm facing a hydration error whenever I change the language and refresh the page. Below is ...

"Attempting to dynamically include Components for SSR bundle in React can result in the error message 'Functions are invalid as a React child'. Be cautious of this

When working with my express route, I encountered an issue trying to pass a component for use in a render function that handles Server-Side Rendering (SSR). Express Route: import SettingsConnected from '../../../client/components/settings/settings-c ...

Enclose a group of tiles in a shrinkwrap div

I've been struggling to make a div adjust to its content size here. I've attempted various methods to shrinkwrap it, but none seem to work. <div class="outer"> <div class="cont"> <img src="http://www.placehold.it/100" ...

Opening a Bootstrap Modal in React without relying on npm react-bootstrap

I've been trying to create a Modal in React.js using Bootstrap5, but I'm unable to use npm react-bootstrap for various reasons. I attempted an approach where I utilized state to set Modal classes with a button, which worked well with my NavBar, b ...

Obtain data in JSON format through an xmlhttp request

I originally used jQuery for this task, but I now want to switch to regular JavaScript as I'll be incorporating it into phonegap. I aim to avoid relying on different JS frameworks every time I make a server request, which could potentially improve per ...

Retrieving the latest entry from the MySQL database

I am encountering an issue with a code that involves fetching data from MySQL into an array. I have a form with color and size select boxes, and when an onclick javascript function is triggered it creates two additional select boxes. I have successfully re ...

How to keep the show/hide effect active in jQuery even when the user presses the backspace

I recently came across this code snippet on a fiddle: https://jsfiddle.net/htz8x1no/ that I'm working with. Here's the code in question: $('.relevant-results').hide(); $('#input').keyup(function() { if ($ ...

Using React PropTypes with Auth0

How can Auth0 be integrated with React PropTypes? index.js import App from '../components/App'; import WelcomeRoute from './Welcome'; import SettingsRoute from './Settings'; import CampaignRoute from './Campaign'; ...

Using Rails to load an image from CSS

My current approach to loading an image is using this code: <div id="bglion"><%= image_tag("BG-LION6.png")%></div>, which successfully displays the image. However, I am interested in loading the image from a CSS file instead. After resea ...

JavaScript loop used to create markers on Google Maps

I am currently in the process of developing a basic Google map which includes markers and involves looping through the data source for the markers. When I replace key.lng or key.lat with hardcoded values in the code below, everything functions correctly. ...

Tips for successfully importing mock data for testing without running into reference problems when reusing the same mocked object or array multiple times

Trying to run tests for Angular has presented a challenge. I have intricate objects, nested within other objects, stored in a separate file along with my mocked data. Each mocked object is linked to an export in the data file specifically created for mock ...

Combine "Speech Recognition" with the text input option

I recently developed a code for "speech to text" functionality, which includes an input type text field. However, when I speak to my computer, the words are not being entered into the input field. Why is this happening? I specifically want the word "Hello" ...

"An error has occurred in the file system, make sure to handle it when

I am encountering an issue with submitting a form using jQuery's ajaxSubmit() function. The problem arises when the file selected in the form is renamed, deleted, or made inaccessible before submission, leading to potential discrepancies in whether th ...

Exploring the Contrast between Using @import for Styles and js Import for Webpack Configuration

While delving into the source code of ant-design, I couldn't help but notice that each component has both an index.ts and a index.less file in the style folder. This got me thinking - why is JavaScript being used to manage dependencies here? What woul ...