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

Develop universal style classifications for JSS within material-ui

Currently, I am utilizing the JSS implementation of material-ui to style my classes. As I have separated my components, I find myself dealing with a significant amount of duplicated code in relation to the components' styles. For instance, I have mu ...

Is it necessary to download all npm packages when starting a new project?

I recently started learning about npm packages and node. I noticed that when installing packages, they create numerous folders in the "node modules" directory. This got me thinking - when starting a new project, do I need to re-install all these packages ...

Exploring the Differences in CSS Styling between Web and Mobile Platforms

Recently, I launched my new website and encountered a peculiar issue. Upon clicking on Pickup Date & Time, a bootstrap datepicker pops up like it should. However, the problem arises when viewing the website on mobile devices - the datepicker appears offsc ...

Using JQuery template: a guide to accessing recently added option elements with JQuery templates

I have a JSON array that needs to be iterated through in order to create HTML option items using the JQuery template. However, I am facing an issue where there are duplicate values within each group of data. For example, 'a' can appear in both gr ...

Creating a list that renders responsively using ReactJS

I'm currently working on implementing a responsive search bar that filters through a list of pure components (up to 100 components displayed at once). However, I've noticed there is a slight half-second delay between typing the first letter and s ...

Fixed Navigation - Employing stickUp.js extension

* { box-sizing: border-box; } body { margin: 0; padding: 0; font-weight: 500; font-family: 'Helvetica Neue', sans-serif; } main {} .bckgrnd { background-position: center center; background-repeat: no-repeat; background-attachment: ...

Guide on deleting an element from an object array based on the content of a specific field (resulting in undefined mapping)

I am working on integrating a task list feature using React. I have created a state to store the id and content of each task: this.state = {tasks: [{id: 123, content: 'Walk with dog'}, {id: 2, content: 'Do groceries'}]} Adding elements ...

Tips for showing a single progress message when uploading multiple files on eleme.io [vuejs]

Tech Stack: Utilizing Vuejs with element.eleme.io framework. Objective: To implement a feature that allows users to upload multiple files while displaying only one "in progress message". To handle image uploads, we are integrating . During the upload pr ...

Choosing a specific page number - kendo grid

Currently, I am working on creating a grid using kendo-telrik. Let's say I have 100 data items, but in the JSON format, I only have 10 data items (assuming each page contains 10 data items for pagination). However, I want to display all the pages (10 ...

Disable or set input text to read-only in Internet Explorer 9 and earlier versions using JavaScript or jQuery

Can anyone offer any suggestions on how to accomplish this task? I attempted using JavaScript with the code below, but it did not yield the desired results. element.readOnly="true"; element.readonly="readonly"; element.disabled="disabled"; I also tried ...

Updating the DOM through Long Polling allows us to maintain existing attributes in jQuery Plugin

UPDATE: The functionality is all set; the pushes are working. The only issue I'm facing is that each push resets the #load_info div to empty. Is there a way to retain the original content inside the div, even though the content will be an updated vers ...

Retrieve files from Amazon S3 using JavaScript

I'm currently working with a javascript file that's intended to download a text file from one of my S3 buckets. However, after running this file using "node file.js", nothing happens and there's no output. Is there something I'm missing ...

When attempting to create a build using npm run, an error with code ELIFECYCLE occurred despite successfully installing

I've been attempting to run the lodash library on my computer. You can find the library here on GitHub. I went ahead and forked the repository, then cloned it onto my system. I successfully installed all dependencies mentioned in the package.json fil ...

Trouble with passing the function variable to setState efficiently

Although I haven't worked with React for a while, it seems like this issue is more related to plain JS. Here is the setState function that I am using: // click event on parent for performance reasons ``Component:`` const [active, setActive] = useSta ...

Encountering an issue with Material-UI and Next.js: "TypeError: theme.spacing is not a function

Encountering an issue after modifying _app.js to dynamically generate a material UI theme. I've been following the implementation example provided by the material-ui team at: https://github.com/mui-org/material-ui/tree/master/examples/nextjs. To summ ...

Preventing template rendering in Angular until an event is triggered - but how?

I am currently working on a directive that functions well, but I had to resort to using inline template code in order to delay rendering until the click event occurs. However, I believe it would be more streamlined if I could assign the directive template ...

JavaScript / Ajax / PHP - A Minor Bug That's Bugging Me

I'm in need of some help, as I feel like I'm losing my mind right now. I've developed a code using php/js/ajax to verify if an email address exists when it's submitted. After testing the ajax, I can confirm that the correct values are ...

Can we determine if a user's operating system has disabled animations?

In my frontend project with React, I am incorporating an animation within a component. However, I want to cater to users who have disabled animations in their settings by replacing the animated content with a static image. Is there a method to detect if ...

A fixed HTML div with a relative div is like having your own

I am in search of two divs with the following styles: <div style="height:20px;" /> <div style="height:100%;" /> These divs result in one being 20px tall and the other spanning 100% of the screen height, causing a vertical scrollbar that is eq ...

What is the best way to add a URL dynamically when a click event occurs?

Here is the code where I am making an API call: export const filteredProducts = (e) => { const radio = e.target.checked; return dispatch => { dispatch({type: actionTypes.TOGGLE_LOAD}); axios.get(radio ? `/store?limit=9&skip=0&subc ...