Is there a way for me to increment the value of 'sessionStorage.fgattempt' whenever either 'fgMade()' or 'threeMade()' are called?

Currently, I am developing a basketball game stat tracker and need to update the field goal attempts every time I make a field goal or three-pointer. Additionally, I am looking for ways to optimize the javascript code provided.

The main requirement is to increment the value of 'sessionStorage.fgattempt' whenever both 'fgMade()' and 'threeMade()' functions are executed. It would also be helpful if the 'threeMade()' function also updated 'sessionStorage.threeattempt'.

<!DOCTYPE html>
<html>

<head>
  <script>
    // JavaScript functions here
  </script>
  <style>
    /* CSS styles here */
  </style>
</head>

<body>
  <table>
    <thead>
      <tr>
        <th>FGM</th>
        <th>FGA</th>
        <th>3PM</th>
        <th>3PA</th>
        <th>BLK</th>
        <th>STL</th>
        <th>DREB</th>
        <th>OREB</th>
        <th>TO</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>
          <div id="result1">N/A</div>
        </td>
        <td>
          <div id="result2">N/A</div>
        </td>
        <td>
          <div id="result3">N/A</div>
        </td>
        <td>
          <div id="result4">N/A</div>
        </td>
        <td>
          <div id="result5">N/A</div>
        </td>
        <td>
          <div id="result6">N/A</div>
        </td>
        <td>
          <div id="result7">N/A</div>
        </td>
        <td>
          <div id="result8">N/A</div>
        </td>
        <td>
          <div id="result9">N/A</div>
        </td>
      </tr>
    </tbody>
  </table>
  <!-- Button elements with event listeners -->
</body>

</html>

Answer №1

It seems like this might be the solution you're seeking. Just a heads up, this code will function even without accessing session storage, which I believe is crucial to include.

// A straightforward way to encapsulate the code into an object
// While still maintaining 'private' properties due to being a self-invoked function.
const App = function(myNameSpace) {
  let state = { // Initial app state
    fgmade: 0,
    fgattempt: 0,
    threemade: 0,
    threeattempt: 0,
    block: 0,
    steal: 0,
    defrebound: 0,
    offRebound: 0,
    turnover: 0
  };


  // A simple method to load the state from session storage
  const loadState = () => {
    try {
      if (sessionStorage.getItem("appState") != null) {
        state = JSON.parse(sessionStorage.getItem("appState"));
      }
    } catch (e) {
      // todo?
    }
  };


  // A simple state method to update the application state in session storage
  const setState = () => {
    try {
      sessionStorage.setItem("appState", JSON.stringify(state));
    } catch (e) {
      // todo?
    }
  };


  // A simple function to reset the state
  const resetState = () => {
    Object.keys(state).forEach(k => state[k] = 0);
    setState();
    render();
  };


  // A VERY simple render method
  const render = () => {
    document.getElementById("result1").innerHTML = state.fgmade;
    document.getElementById("result2").innerHTML = state.fgattempt;
    document.getElementById("result3").innerHTML = state.threemade;
    document.getElementById("result4").innerHTML = state.threeattempt;
    document.getElementById("result5").innerHTML = state.block;
    document.getElementById("result6").innerHTML = state.steal;
    document.getElementById("result7").innerHTML = state.defrebound;
    document.getElementById("result8").innerHTML = state.offRebound;
    document.getElementById("result9").innerHTML = state.turnov...
      
// The bulk of the code determines which property to update
const buttonClickHandler = (e) => {
const txt = e.target.textContent.replace(/\ /g, '').toUpperCase();

switch (txt) {
case 'FGM':
updateProperty('fgmade');
updateProperty('fgattempt');
break;

...


// Make sure to return the public object
return myNameSpace;
}({});


// Very basic solution for document.ready
setTimeout(App.launch, 250);
table,
th,
td {
border: 1px solid black;
}

button#reset {
background: red;
border-color: red;
color: white;
}
<table>
<thead>
<tr>
<th>FGM</th>
<th>FGA</th>
<th>3PM</th>
<th>3PA</th>
<th>BLK</th>
<th>STL</th>
<th>DREB</th>
<th>OREB</th>
<th>TO</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<div id="result1">N/A</div>
</td>
<td>
<div id="result2">N/A</div>
</td>
<td>
<div id="result3">N/A</div>
</td>
<td>
<div id="result4">N/A</div>
</td>
<td>
<div id="result5">N/A</div>
</td>
<td>
<div id="result6">N/A</div>
</td>
<td>
<div id="result7">N/A</div>
</td>
<td>
<div id="result8">N/A</div>
</td>
<td>
<div id="result9">N/A</div>
</td>
</tr>
</tbody>
</table>



<p><button>FGM</button></p>
<p><button>FGA</button></p>
<p><button>3PM</button></p>
<p><button>3PA</button></p>
<p><button>BLK</button></p>
<p><button>STL</button></p>
<p><button>DREB</button></p>
<p><button>OREB</button></p>
<p><button>TO</button></p>
<p><button id="reset">RESET</button></p>

Answer №2

Just my thoughts...

    var
      basketball_scores_head = document.querySelector('#basketball-scores thead tr'),
      basketball_scores_body = document.querySelector('#basketball-scores tbody tr'),
      All_ScoreButton        = document.querySelectorAll('#basketball-scores  button'),
      Scores_Vals            = {},
      asStorage              = (typeof(Storage) !== "undefined");
    ;

    All_ScoreButton.forEach(bt_elm=>{
      let
        e_TH = document.createElement('th'),
        e_TD = document.createElement('td'),
        ref  = bt_elm.dataset.count.split(' ')[0]
        ;
      e_TH.textContent = ref;
      e_TD.textContent = "N/A";
      e_TD.id          = "count_"+ref;

      basketball_scores_head.appendChild(e_TH);
      basketball_scores_body.appendChild(e_TD);

      Scores_Vals[ref] = 0;

      bt_elm.onclick = IncreaseScore;
    });

    if (asStorage) {
      if ( sessionStorage.getItem('basketball_scores') )
      {
        Scores_Vals = JSON.parse( sessionStorage.getItem('basketball_scores'));
        for (let cnt in Scores_Vals ) {
          document.getElementById("count_"+cnt).textContent = Scores_Vals[cnt].toString();
        };
      } else {
        sessionStorage.setItem('basketball_scores',  JSON.stringify(Scores_Vals) );
      }
    }

    function IncreaseScore(e) {
      e.target.dataset.count.split(' ').forEach (cnt =>{
        Scores_Vals[cnt]++;
        document.getElementById("count_"+cnt).textContent = Scores_Vals[cnt].toString();
      });
      if (asStorage) {
        sessionStorage.setItem('basketball_scores',  JSON.stringify(Scores_Vals) );
      }
    }
      table#basketball-scores,
      table#basketball-scores th,
      table#basketball-scores td {
        border : 1px solid grey;
      }
      table#basketball-scores th,
      table#basketball-scores td {
        width  : 100px;
      }
      table#basketball-scores button {
        font-weight: bold;
        margin-top: 10px;
      }
<table id="basketball-scores">
  <thead>
    <tr></tr>
  </thead>
  <tbody>
    <tr></tr>
  </tbody>
  <tfoot>
    <tr>
      <td><button data-count="FGM FGA">+</button></td>
      <td><button data-count="FGA">+</button></td>
      <td><button data-count="3PM FGA">+</button></td>
      <td><button data-count="3PA">+</button></td>
      <td><button data-count="BLK">+</button></td>  
      <td><button data-count="STL">+</button></td>
      <td><button data-count="DREB">+</button></td>
      <td><button data-count="OREB">+</button></td>
      <td><button data-count="TO">+</button></td>
    </tr>
  </tfoot>
</table>

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

Enhance the visual appeal of Autodesk Forge Viewer by incorporating environmental textures

Is there a way to incorporate an environmental texture into Autodesk Forge Viewer v6.0? I know in Three.js you can apply a texture to the scene's background and environment, so how would I achieve this in APS viewer? I'm not looking for a skybox ...

Is there a way to verify if a user taps outside a component in react-native?

I have implemented a custom select feature, but I am facing an issue with closing it when clicking outside the select or options. The "button" is essentially a TouchableOpacity, and upon clicking on it, the list of options appears. Currently, I can only cl ...

What are some best practices for integrating CSS grid layouts with React for optimal results?

My current project involves developing a Single Page Application using ReactJs and CSS grid layouts for styling components. However, I've encountered an issue where the two technologies do not seamlessly integrate: CSS grid layouts are typically appli ...

Is it possible for me to alter the script for my button's onclick

Is there a way to replicate all properties of a div when creating a clone using JavaScript code? I have an existing script that successfully creates a clone of a div when a button is pressed, but it does not copy the CSS properties. How can I ensure that t ...

Tips for successfully retrieving a variable from a function triggered by onreadystatechange=function()

Combining the ajax technique with php, I'm looking to extract the return variable from the function called by onreadystatechange. A java function triggers a call to a php script upon submission, which then validates certain data in the database and r ...

What is the best way to update and override multiple nested NPM dependencies with various versions?

Apologies for not being fluent in English Here is my NPM dependency: dependency tree +-- <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6c1e090d0f184108091a4105021f1c090f18031e2c5d4255425c">[email protected]</a> ...

Launch a new window for a div when a button is clicked

Hey everyone, I need some help with opening a div in a new window. Currently, I am using window.open and it is working fine. Here is the code snippet: <div id="pass">pass this to the new window</div> <a href="#" onclick="openWin()">clic ...

react-i18next - The function call does not match any overload when the specified type is `string`

I am currently utilizing react-i18next in conjunction with React and TypeScript. Interestingly, when I attempt to load a property using a string literal and type inference, everything works seamlessly. However, once I specify the type as string, an error i ...

Node and Web scraping Promise: a powerful combination

I've been using Cheerio and Node for web scraping, and I thought implementing promises could simplify handling asynchronous code. However, my attempt to chain promises hasn't been successful. Below is the code I'm working with, in hopes that ...

Utilizing jQuery to manage asynchronous tasks, such as executing AJAX requests, handling promises, and using deferred

Exploring My jQuery Plugins: (function ($, window, document, undefined) { $.fn.loadPageContent = function (url, dataToSend) { url = url || window.location.href; dataToSend = dataToSend ? dataToSend : {}; return $.post(url, data ...

The operation of my NodeJS application suddenly halts

In my project, I have a Server.js file that I run from the command line using: node server Within the Server.js file, a new instance of class A is created Class A then creates instances of both class B (web socket) and class C (REST API) If the web socket ...

Error encountered in NodeJS after refreshing the node server

I am currently in the process of developing a web application using Node.js, Express framework, and EJS templates. Below is the code snippet for my server setup: const express = require('express'); const app = express(); const PORT = process.en ...

Tips on updating route and content dynamically without triggering a page reload while ensuring search engine indexing compatibility

I am curious to find a way to change the URL displayed and have it reflect different content on the page, all while ensuring that it is search engine friendly for indexing by robots. I have experimented with using AJAX for dynamic data loading and angular ...

How to Target a Specific Element Using its Class with jQuery

Hey there! I'm currently working with the following snippet of HTML code: <li class="grey"> <div class="row"> <button id="test" style="width:50%;" class="btn btn-blue-white cartBtn">Add to Cart</button> </div ...

What are the best practices for effectively utilizing the nodejs Stream API?

I am currently working on an application that reads input from various sources, including files, sockets, and other parts of the same program that produce buffers or strings. While I have successfully handled sockets and files using node's Stream API ...

What is the preferred method for writing `*zoom: 1;` in CSS?

Trying to create my code, I decided to borrow some CSS files from older code. However, upon running yarn build I encountered several errors like: ▲ [WARNING] Expected identifier but found "*" [css-syntax-error] <stdin>:122:2: 122 │ * ...

The problem with clearing floats in IE7 (as well as 6)

Currently, I am facing an issue where I have a list that I want to split into three columns by using the float left property and then clearing the first column. Everything seems to be working fine in IE8 and FF, however, IE7 is causing the second column t ...

Can someone show me how to implement RequestPromise in TypeScript?

I recently integrated the request-promise library into my TypeScript project, but I am facing some challenges in utilizing it effectively. When attempting to use it in the following manner: import {RequestPromise} from 'request-promise'; Reque ...

Having problems with loading @font-face in Ionic Framework Android app build?

While working on an app in Ionic Framework, I encountered a peculiar issue. https://i.stack.imgur.com/xk8uD.png In my Ionic Framework application, I am importing @font-face and running the app on an Android device (Galaxy SIII). Strangely, the font (Mont ...

Load image in index.html for use on a different webpage

I'm looking to preload a large image that serves as the background on another page of my website. By preloading this image, I hope to ensure that when users first visit my webpage, the image is ready to load instantly when they eventually navigate to ...