Displaying the recorded text in red when the stop button is clicked

I have a query about html, css, javascript.

I've developed a game where numbers need to be clicked in a specific order.

Upon clicking the stop button midway through the game, I want to display the record time in red color like shown in this image: enter image description here

I also have some hints.

  1. Utilize the following code:
newP.className = "stopped";
  1. Use CSS selector by class name
  2. Create division: Game success, Game stop

Here's my complete code snippet.

var answer = 0;

function start() {
  startTime = new Date().getTime();
  toggleButton = document.getElementById("toggle_button");
  toggleButton.innerHTML = "Stop";
  toggleButton.onclick = stop;

  init();

  timer = setInterval(function() {
    now = new Date().getTime();
    seconds = now - startTime;
    document.getElementById("time").innerHTML = displayTime(seconds);
  }, 60);
}

function stop() {
  clearInterval(timer);
  toggleButton = document.getElementById("toggle_button");
  toggleButton.innerHTML = "Start";
  toggleButton.onclick = start;
}

function btnClick(num) {
  btns = document.getElementsByClassName("btn");
  if (num == answer) { 
    answer = answer+1;
    btns[num].disabled = true;
    if (num == 8) { 
      stop();
      score = document.getElementById("time").innerHTML;
      newP = document.createElement("p");
      newP.appendChild(document.createTextNode(score));
      document.getElementById("score_board").appendChild(newP);
    }
  } else { 
    init();
  }
}

function init() {
  answer = 0;

  btns = document.getElementsByClassName("btn");
  for (let index=0; index<btns.length; index++) {
    btns[index].disabled = false;
    btns[index].innerHTML = index;
  }
}

function displayTime (seconds) {
  m = String(Math.floor(seconds / 1000 / 60));
  s = String(Math.floor((seconds / 1000) % 60));
  ms = String(Math.floor(seconds % 100));
  return m.padStart(2, '0') + ":" + s.padStart(2, '0') + ":" + ms.padStart(2, '0');
};
.btn {
  width:60px;
  height:60px;
  font-size:18px;
  margin:2px;
} /*select by class */

#toggle_button {
  width:120px;
  background-color:#000;
  color:#fff;
  height:24px;
  border:none;
}

#time {
  font-size:20px;
  font-weight:bold;
} /*select by id */

img {
  width:100px;
} /*select by html elemnt */
<center>
  <p id="time">00:00:00</p>
  <button id="toggle_button" onclick="start()">Start</button>
  <br /><br />

  <button id="button_1" class="btn" onclick="btnClick(0)" disabled>?</button>
  <button id="button_2" class="btn" onclick="btnClick(1)" disabled>?</button>
  <button id="button_3" class="btn" onclick="btnClick(2)" disabled>?</button><br />
  <button id="button_4" class="btn" onclick="btnClick(3)" disabled>?</button>
  <button id="button_5" class="btn" onclick="btnClick(4)" disabled>?</button>
  <button id="button_6" class="btn" onclick="btnClick(5)" disabled>?</button><br />
  <button id="button_7" class="btn" onclick="btnClick(6)" disabled>?</button>
  <button id="button_8" class="btn" onclick="btnClick(7)" disabled>?</button>
  <button id="button_9" class="btn" onclick="btnClick(8)" disabled>?</button>

  <div id="score_board">
    <p><strong>Score Board</strong><p>
  </div>
</center>

Apologies for any language errors as English is not my native tongue. Thank you very much...!

Answer №1

In the code snippet below, the change in the stop function is highlighted. If the stop function has a parameter, the color will be set to red. When the user presses the stop button, HTML sends a press action as a parameter. However, when the game is completed, the function is called without a parameter. This allows you to display the score in red when the user breaks the game and black when the user completes it.

const scoreBoard = document.querySelector('#score_board');
const score = document.getElementById("time").innerHTML;
const scoreEl = document.createElement('p');
if(c) scoreEl.style.color = 'red';
const node = document.createTextNode(score);
scoreEl.appendChild(node);
scoreBoard.appendChild(scoreEl);

Below is an example:

var answer = 0;

function start() {
  startTime = new Date().getTime();
  toggleButton = document.getElementById("toggle_button");
  toggleButton.innerHTML = "Stop";
  toggleButton.onclick = stop;

  init();

  timer = setInterval(function() {
    now = new Date().getTime();
    seconds = now - startTime;
    document.getElementById("time").innerHTML = displayTime(seconds);
  }, 60);
}

function stop(c) {
  clearInterval(timer);
  const scoreBoard = document.querySelector('#score_board');
  const score = document.getElementById("time").innerHTML;
  const scoreEl = document.createElement('p');
  if(c) scoreEl.style.color = 'red';
  const node = document.createTextNode(score);
  scoreEl.appendChild(node);
  scoreBoard.appendChild(scoreEl);
  toggleButton = document.getElementById("toggle_button");
  toggleButton.innerHTML = "Start";
  toggleButton.onclick = start;
}

function btnClick(num) {
  btns = document.getElementsByClassName("btn");
  if (num == answer) { 
    answer = answer+1;
    btns[num].disabled = true;
    if (num == 8) { 
      stop();
    }
  } else { 
    init();
  }
}

function init() {
  answer = 0;

  btns = document.getElementsByClassName("btn");
  for (let index=0; index<btns.length; index++) {
    btns[index].disabled = false;
    btns[index].innerHTML = index;
  }
}

function displayTime (seconds) {
  m = String(Math.floor(seconds / 1000 / 60));
  s = String(Math.floor((seconds / 1000) % 60));
  ms = String(Math.floor(seconds % 100));
  return m.padStart(2, '0') + ":" + s.padStart(2, '0') + ":" + ms.padStart(2, '0');
};
.btn {
  width:60px;
  height:60px;
  font-size:18px;
  margin:2px;
} /*select by class */

#toggle_button {
  width:120px;
  background-color:#000;
  color:#fff;
  height:24px;
  border:none;
}

#time {
  font-size:20px;
  font-weight:bold;
} /*select by id */

img {
  width:100px;
} /*select by html element */
<center>
  <p id="time">00:00:00</p>
  <button id="toggle_button" onclick="start()">Start</button>
  <br /><br />

  <button id="button_1" class="btn" onclick="btnClick(0)" disabled>?</button>
  <button id="button_2" class="btn" onclick="btnClick(1)" disabled>?</button>
  <button id="button_3" class="btn" onclick="btnClick(2)" disabled>?</button><br />
  <button id="button_4" class="btn" onclick="btnClick(3)" disabled>?</button>
  <button id="button_5" class="btn" onclick="btnClick(4)" disabled>?</button>
  <button id="button_6" class="btn" onclick="btnClick(5)" disabled>?</button><br />
  <button id="button_7" class="btn" onclick="btnClick(6)" disabled>?</button>
  <button id="button_8" class="btn" onclick="btnClick(7)" disabled>?</button>
  <button id="button_9" class="btn" onclick="btnClick(8)" disabled>?</button>

  <div id="score_board">
    <p><strong>Score Board</strong><p>
  </div>
</center>

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

Changing the visibility of a button based on a checkbox in JavaScript - here's how

Just starting out with JS and working on a react project. I need to toggle the visibility of a button from false to true when a checkbox is checked. Here's my code, I believe the logic is correct but it's not updating the UI. Any suggestions are ...

I am encountering issues with setting a background image in Bootstrap 3.1.1 while trying to achieve a par

I'm struggling to add a background image to my bootstrap site. I'm attempting to create a parallax site using stellar.js, and while the site is functional with text on each slide and correct scrolling links, the images just won't load. Despi ...

What is the best method for retrieving data through an ajax call in my modular JavaScript setup?

Working with a basic modular JavaScript structure, my goal is to request a random quote from an API and display it on an HTML page using Mustache.js. I previously achieved this without the modular approach, but now I'm attempting it in a more structur ...

`How can a child component in Next.js send updated data to its parent component?`

Currently diving into Next.js and tinkering with a little project. My setup includes a Canvas component alongside a child component named Preview. Within the Preview component, I'm tweaking data from the parent (Canvas) to yield a fresh outcome. The b ...

AngularJS: Issues with retrieving response headers following a $resource $save operation

When I run the $save function, which triggers my angularJS $resource to send a POST request to my API, everything seems to be working fine. I can successfully debug into the success callback handler and confirm that the object is created in my API. myObj. ...

The event is not functioning properly with jquery

<div id="form"> <form action=""> <input type="button" id="sub"/> </form> </div> Upon clicking the submit button, the content will be dynamically changed using jQuery. Here is the jQuery code: $(document).ready(function() { ...

Creating a website with a responsive design that perfectly adapts to different screen sizes, starting with my 1920x1080

've been working on designing a website using Dreamweaver CS6, and during this process, I encountered some challenges. Initially, I set everything up based on hard pixel values for div and image sizes, but realized that this caused severe breaks in th ...

Leveraging Window Object in Custom Hooks with NextJS

ReferenceError: window is not defined This issue arises on the server side when NextJS attempts to render the page. However, it is possible to utilize window within the useEffect hook by following the guidance provided here. I am seeking advice on creati ...

Upgrading Xeditable button designs using AngularJS

Have a query. Can you replace the save(submit) button and cancel buttons with links in Xeditable for AngularJS? Appreciate your help ...

Converting from CAPS lock to using the capitalize property in CSS

Is there a way to transform a sentence that is all in CAPs lock without changing it? This sentence is part of a paragraph, and I am looking for a CSS solution (maybe with a little Jquery) that works reliably across most devices! I have come across similar ...

Leveraging Mozilla FormData in conjunction with a jquery $.ajax request

In my current project, I am utilizing HTML5 features to enable drag and drop functionality for files. As part of this implementation, I need to submit form data along with the files in a multipart/form-data request using the Mozilla FormData() API. I am ut ...

Tips for implementing an onclick jquery function within an input field

Just starting out with JavaScript and jQuery, I have a jQuery function that looks like this: $('.input-group .date').datepicker({ }); I want to apply it to the following HTML structure: <div class="input-group date" id="dp3"> <inp ...

Extracting data from web pages using JavaScript and PHP

Using the following script, I am able to scrape all the items from this specific page: $html = file_get_contents($list_url); $doc = new DOMDocument(); libxml_use_internal_errors(TRUE); if(!empty($html)) { $doc->loadHTML($html); ...

Determine the latest date within each group and display the corresponding output value

I am seeking a way to showcase only the most recent value for each group. For example, in the CSV data provided below, the total amount of Bagels in the Cinnamon Raisin variety were collected during three different sampling periods: May 2017, March 2017, ...

What is the best way to simulate an external class using jest?

My Vue page code looks like this: <template> // Button that triggers the submit method </template> <script> import { moveTo } from '@/lib/utils'; export default { components: { }, data() { }, methods: { async ...

Using jQuery to trigger a function from an AJAX call

I'm facing an issue with calling a function upon successful completion of my AJAX request. Here is what I have attempted so far: function dtMRPReasonCode(dt) { var data = null; jQuery.ajax({ ...

Swapping out images by clicking on a thumbnail, featuring numerous occurrences on a single webpage

I'm currently working on a project where I need to display several large images with corresponding thumbnails. When a user clicks on a thumbnail, I want the larger version of that thumbnail to replace the current large image. While I have successfull ...

Webpage not resizing when WebView orientation changes

While developing my android app, I encountered an issue with the WebView. When I am at the very top of the WebView and switch my phone to landscape mode, the webpage does not resize properly to fit the screen. It only takes up half of the screen. However, ...

Update the array with the new data by setting the state

Is it possible to edit and save data in an array while iterating through it using this.state.data.map()? If so, what is the best approach to achieve this? Check out this live example for reference. Below is a sample code snippet: class App extends React ...

Conflicting media queries

Attempting to resolve the issue of site content overlapping with the background slider plugin on a WordPress website, I have encountered conflicting media queries for different devices. While it may work perfectly on mobile devices, it can create problems ...