MTG Life counter. Display fluctuations in count

I am currently working on a fun project creating an MTG (Magic The Gathering) life tracker, even though the code is quite messy. Despite its flaws, it still gets the job done.

Click here to view the MTG life tracker


https://i.stack.imgur.com/Su17J.png



Objective / Challenges I'm facing

My goal is to incorporate an indicator that displays how many times someone has adjusted the life total of one of the players by clicking a button. This indicator would briefly show the number of clicks before fading out, essentially resetting for the next adjustment.

If the life total is adjusted again, the indicator should visualize the changes made, both up and down. Is there a straightforward way to achieve this using jquery or vanilla JS?

If not, I might resort to utilizing jquery's .change

.change(function(){//"count recent clicks somehow"
function to track the clicks and display a + or - accordingly.

Any advice or assistance on this matter would be greatly appreciated!


Answer №1

I ended up complicating things way too much

Check out this example of it in action!

var lastFadeOutTime = 0;
var fadeOutTimeout;

function modifyLife(player, amount) {
  var lifeTotalElement = $(`#lifeTotal${player.charAt(player.length-1)}`);
  var historyLogElement = $(`#historyLog${player.charAt(player.length-1)}`);
  var visualizationElement = $('#visualization');

  var currentLife = parseInt(lifeTotalElement.text());
  var newLife = currentLife + amount;

  // Update life total
  lifeTotalElement.text(newLife);

  // Update history log
  var historyItem = amount > 0 ? `+${amount}` : `${amount}`;
  historyLogElement.prepend(`<p>${historyItem}</p>`);

  // Update visualization
  var totalChanges = 0;

  // Only consider changes after the last fade out
  historyLogElement.find('p').slice(0, 1000).each(function() {
    totalChanges += parseInt($(this).text());
  });

  // Update visualization
  visualizationElement.text(`${totalChanges}`);
  visualizationElement.fadeIn();

  // Clear the previous timeout
  clearTimeout(fadeOutTimeout);

  // Hide visualization after 5 seconds and reset the history log
  fadeOutTimeout = setTimeout(function() {
    var currentTime = new Date().getTime();
    if (currentTime - lastFadeOutTime >= 3000) {
      visualizationElement.fadeOut(function() {
        historyLogElement.find('p').remove();
        lastFadeOutTime = currentTime;
      });
    }
  }, 5000);
}
body {
  font-family: 'Arial', sans-serif;
  text-align: center;
}

.container {
  display: flex;
  justify-content: space-around;
  margin: 20px;
}

.player {
  width: 150px;
  padding: 10px;
  border: 2px solid #333;
  border-radius: 5px;
}

.life-total {
  font-size: 24px;
  margin-bottom: 10px;
}

.btn {
  padding: 8px 16px;
  font-size: 16px;
  cursor: pointer;
}

.history-log {
  display: none;
  /* hide history log */
}

.visualization {
  margin-top: 20px;
  font-size: 18px;
  display: none;
  /* initially hide */
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Magic: The Gathering Life Counter</title>
</head>

<body>
  <div class="container">
    <div class="player" id="player1">
      <h2>Player 1</h2>
      <div class="life-total" id="lifeTotal1">40</div>
      <button class="btn" onclick="changeLife('player1', 1)">+1</button>
      <button class="btn" onclick="changeLife('player1', -1)">-1</button>
      <div class="history-log" id="historyLog1"></div>
    </div>

    <div class="player" id="player2">
      <h2>Player 2</h2>
      <div class="life-total" id="lifeTotal2">40</div>
      <button class="btn" onclick="changeLife('player2', 1)">+1</button>
      <button class="btn" onclick="changeLife('player2', -1)">-1</button>
      <div class="history-log" id="historyLog2"></div>
    </div>
  </div>
  <div class="visualization" id="visualization"></div>
  <script src="https://code.jquery.com/jquery-3.6.4.min.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

navigate to a new page in vue with node.js

As I continue to expand my knowledge in JavaScript, Vue, and Node.js, I encountered a specific issue that I need help with. My goal is to redirect the Vue page after logging in using Node.js. Below you'll find the code snippets for my Vue setup and sc ...

What is the most efficient way to find the sum of duplicates in an array based on two different properties and then return the

var data = [ { "amount": 270, "xlabel": "25-31/10", "datestatus": "past", "color": "#E74C3C", "y": 270, "date": "2020-10-31T00:00:00Z", "entityId": 1, "entityName": "Lenovo HK", "bankName": "BNP Paribas Bank", "b ...

Desktop display issue: Fontawesome icon not appearing

Having trouble getting the fontawesome icon to display properly on my website. It appears in inspect mode, but not on the actual site itself. Any suggestions on how to fix this issue? import React, { Fragment, useState} from "react"; import { Na ...

Struggling with displaying MySQL data in JSON format using Highcharts

Currently, I am attempting to display data from a PHP file on an area graph by using the example found here. Initially, all the data was commented out before being passed to the array. Now, my focus is solely on displaying one portion of the data. I suspec ...

The Ajax request is not successfully communicating with the PHP script

I am struggling with an issue regarding ajax calling a PHP code without changing the current page. Despite checking the php_error.log, I cannot find any reference to the PHP file. There are no errors displayed on screen, leaving me clueless about how to re ...

Necessary CSS selector input equivalent in Reactive Forms

Is there a similar CSS method like input:required {CSS} to style all the reactive form fields in Angular that are set as required using Validators.required in their formControl? Or is there another approach to achieve this with CSS? ...

Is a single f.select impacting another f.select in the same form? (undesired)

I am facing an issue where adding a new HTML element like: <%= f.date_select :date, { id: "date-select"} %> is impacting my existing collection select: <%= f.collection_select :id, Customer.where(business_id: current_c ...

Selenium: Utilizing the get_attribute() function with a CSS query

I am attempting to retrieve the value of the title attribute. There are multiple links on the page and I need to specifically select the first link and extract its title attribute. Here is the selenium command that I have used: self.se.get_attribute("c ...

Steps to efficiently enumerate the array of parameters in the NextJS router:

In my NextJS application, I have implemented a catch all route that uses the following code: import { useRouter} from 'next/router' This code snippet retrieves all the parameters from the URL path: const { params = [] } = router.query When I co ...

Filtering data with AngularJS upon user clicks

Encountering a perplexing issue at the moment. I have created buttons using ng-repeat and my intention is for them to filter my list when clicked on. However, I am facing an issue where the list fails to filter upon clicking. Here are the buttons: <div ...

Ways to implement real-time search feature in Rails 4.2

Struggling to implement a basic search form with AJAX in my Rails 4.2 app, I've scoured numerous tutorials without success. Ruby on Rails Live Search (Filtering), https://www.youtube.com/watch?v=EqzwLUni2PM) This is the search method I'm usi ...

What is the technique for implementing a slide animation on hover to move a div identified by the class `box`?

How can I create a div element with the class of box that already has some transitions applied to it, and also include a slide animation on hover effect for the same div? .box { background-color: red; width: 70px; height: 70px; transition-propert ...

Blend field and JavaScript functions while retrieving data from MongoDB

Take a look at this information: { "creation_date" : ISODate("2015-02-10T03:00:00.000Z"), "days_of_validity": 10 } I need to find all documents where "creation_date" is less than today - "days_of_validity" This is what I have come up with so far: doc ...

What is the best way to submit several files along with additional fields simultaneously using FormData?

I have a collection called pocketbase that consists of fields like name, image, and order. My goal is to upload all the images with unique names and in parallel using the power of FormData. Take a look at my code below: export default function AddPhotosAd ...

Do we really need to create our own action creators in Redux Toolkit?

As I delve into implementing the redux toolkit in my react projects, I've come up with a structure for writing slices using redux-thunk to handle API requests. import { createSlice } from "@reduxjs/toolkit"; import axios from "axios&quo ...

"Exploring the dynamic duo of Angular2 and ng2Material

I am currently facing an issue with the styling in my code while using ng2Material with Angular2. First: A demonstration of Material style functioning properly can be seen in this plunker. When you click on the button, you will notice an animation effect. ...

Nested child objects causing interference with mouseenter and mouseleave events

At the start, I am concealing a control panel known as myNestContainer. There is a button called navMyNest that, upon hovering, displays the myNestContainer. This functionality is working well. The problem arises when users try to explore the control pane ...

Ways to verify if a variable holds a JSON object or a string

Is it possible to determine whether the data in a variable is a string or a JSON object? var json_string = '{ "key": 1, "key2": "2" }'; var json_string = { "key": 1, "key2": "2" }; var json_string = "{ 'key': 1, 'key2', 2 } ...

Avoid directing to target selectors when using jQuery UI tabs

Incorporating jQuery tabs into my form with two tabs has been a success, mirroring the demo structure almost perfectly. <div id="tabs"> <ul> <li><a href="#tabs-one">Tab 1</a></li> <li><a href="#tabs-two">Tab ...

Combine the input element's value with a string using jQuery

I am looking to combine the content of an input element into a string using jQuery I am experiencing difficulties appending the content of the input element at the end of the string. Simply using companyString or #companyString is not producing the desir ...