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

Reposition icons accordingly while incorporating a new set of icons

After creating a new icon set font, I noticed that the icons are not positioning correctly and appear smaller than expected when loaded: https://i.stack.imgur.com/1OsAL.png https://i.stack.imgur.com/zmLQq.png I attempted to adjust the .icon class by add ...

correcting mistakes in the design of the website

After inserting Google Adsense on my website, the content of the site moved down. Is there a way to have the content appear alongside the Google Adsense rather than below it? You can view my site here: .wrapper { width: 990px; margin: 0 auto; ...

Is there a way to transfer a value set from one tpl file to another tpl file in cscart using smarty template engine?

I am trying to retrieve the value of a variable set using an input tag from one tpl file. Here is the input tag in A.tpl file: <input type="checkbox" class="checkbox" name="payment_data[processor_params][enable_addbillcard]" id="optional_enable_addbil ...

When the textfield mui is set to shrink, an additional space appears in the label when using a font size of 12px

Struggling to customize the appearance of the textField component, particularly with the label when it is minimized: import * as React from "react"; import TextField from "@mui/material/TextField"; import { createTheme } from "@mui ...

Using Jquery to loop through various select options within a designated container div

I am seeking a way to loop through multiple select options within a specific div using the jQuery each function. If any field is left empty during this iteration, I would like the loop to break and set the reqCourseFlag variable to 0. The current implement ...

Angularjs does not seem to be rendering content placed within curly braces

I'm working on setting up a page with Angular, and I'm facing an issue with displaying JSON data received from the server. Here is the code snippet: HTML <body ng-app="App"> <nav class="navbar navbar-dark bg-inverse navbar-fixed-top"& ...

Ajax external variable

I successfully uploaded a json file via Ajax using vanilla JS. { "list": [ {"name": "Executor", "date": "19.04.2017, 12:32:57"}, ... ] } Although I am able to change the "date" value for the current one using addEventListener, my challenge no ...

Creating a personalized design for Bootstrap Badge

Looking to customize the shape of bootstrap badges from the default ellipse to a rectangle with rounded corners. Any tips on the best approach to accomplish this? ...

Incorrect media type linked to Gmail API attachment error

I need help sending a message via the Gmail API in JavaScript, including a JPEG file attachment. My code so far looks like this: $.ajax({ type: "POST", url: "https://www.googleapis.com/upload/gmail/v1/users/me/messages/send?uploadType=multipart", he ...

Is there a way to eliminate the additional and varying pseudo-padding on text inputs in both Webkit and Gecko browsers?

The issue I'm facing is specific to input[type="text"] elements in Webkit. No matter what adjustments I make, it seems like there is an additional padding: 1px 0 0 1px (top and left only) applied to the element. A similar anomaly occurs in Gecko as w ...

What is the best way to create non-standard text wrapping in HTML and CSS that is both semantic and sleek, avoiding square or circular shapes?

Is there a way to achieve text wrapping like this using semantic and clean HTML and CSS that is compatible with all browsers? The only solution I can think of is adding different classes to the <p> element. However, the drawback of this approach is ...

A guide on using jQuery to cycle through every row of every table on an HTML page

I am trying to figure out the correct syntax for nesting two loops within each other in jQuery. The first loop should iterate over each table in an HTML page that does not have any IDs or classes, while the second loop should go through each table row of t ...

iPhone-compatible iFrame with adaptable webpage dimensions

While attempting to embed our page on a client's site, everything looks great in a browser and our media queries are functioning properly. However, we encountered an issue when viewing the embedded page inside an iframe on an iDevice. It seems that th ...

Utilizing HTML5 Canvas for Shadow Effects with Gradients

Surprisingly, it seems that the canvas API does not support applying gradients to shadows in the way we expect: var grad = ctx.createLinearGradient(fromX, fromY, toX, toY); grad.addColorStop(0, "red"); grad.addColorStop(1, "blue"); ctx.strokeStyle = gra ...

Choosing multiple options in a select tag leads to an error

I am facing an issue with my array and select multiple fields. I want all the select options to be automatically selected using the array ID when the file is loaded. Here is my array: Array( [0] => 3 [1] => 5 [2] => 9 ) This is what my select field loo ...

Enhancing Chat: Updating Chat Messages in Real-Time with Ember.js and Firebase

I recently started working with ember.js and firebase. Right now, I have successfully implemented a feature to post messages and view them in a list format as shown below: //templates/show-messages.hbs {{page-title "ShowMessages"}} <div clas ...

React Virtualized - Blank screen issue occurring because of continuous scrolling through a large list of ITSM items

I am currently working on a lengthy list of items and utilizing the react-virtualized library for this purpose. However, I have encountered an issue that needs addressing. https://i.stack.imgur.com/ROdjp.gif Upon attempting to scroll down for 2 seconds, ...

Steps to utilize a PHP include for displaying HTML content corresponding to the URL file name

I am currently working on a PHP script that utilizes PHP include to insert HTML content based on the filename from the URL. For instance, with the use of PHP include: - if the filename in the URL is dog.html, it will display dog within the HTML document. ...

How can you conceal an HTML element when the user is using an iOS device?

I need the code to determine if a user is using an iOS device and, if not, hide the HTML input type "Play" button. So, I'm uncertain whether my iOS detection is correct, the hiding of the "Play" button in the code, or both: <!DOCTYPE html> < ...

Next.js experiencing development server compile errors and broken page routing in production builds

Howdy everyone! I'm currently working on an app using Next.js. Every time I make a change, the server automatically compiles with the updates, but unfortunately, the pages often fail to render properly. Sometimes it takes several minutes for them to l ...