HTML ISSUES - How do I make it so when Dynamic page change, highchart display different value from my google spread sheet

Question: -
HTML ISSUES - How do I make it so when Dynamic page change, highchart display different value from my google spread sheet.

  • (Keep in mind where its a link I will write link cuz I am new user in forumand can’t post more than 2 links) REPLACE {LINK} WITH https:// and {www} means www

Product:
Wix Studio

What are you trying to achieve:
This is difficult to explain but. I have multiple items with different serials like
0001-12 | 0002-49| 0003-2 that have limited number of serials so I need
when its like 0001 it chart uses this data
something like this: case ‘0001’:
btcIndex = 4; rapIndex = 5; usdIndex = 6; volumeIndex = 7;
break;
when its 0002 chart uses this data
case ‘0002’:
btcIndex = 8; rapIndex = 9; usdIndex = 10; volumeIndex = 11;
break;
The ISSUE is that when I fetch url it keeps doing this

Current URL: {LINK}{www} -cryptocollectors-net.filesusr.com/html/c08a51_3810ea4….html

c08a51_3810ea49bebf5…2ead290cb28.html:23 Match result: null

c08a51_3810ea49bebf5…2ead290cb28.html:27 No valid identifier found in the URL. Ensure the URL format is ‘/item/XXXX-YYYY’.

(anonymous) @ c08a51_3810ea49bebf5…2ead290cb28.html:27

:despair: and then when I test in the console the code on its own it works but when I try to put it in the chart it fetches some random {LINK}{www} -cryptocollectors-net.filesusr.com/html/c08a51_3810ea4….html ← this thing all the time

What have you already tried:
bunch of things. I tried to rewrite the code many times the issue it that it always takes the Iframe or whatever thing as the URL instead of the page url :despair:

Additional information:

  • I have a different code that is one pages 1 by 1 and the chart work but the issue is that when I try to link it to a url in dynamic is when it keeps linking to {LINK}{www} -cryptocollectors-net.filesusr.com/html/c08a51_3810ea4….html when the page url is like {LINK}{www} .cryptocollectors.net/item/0003-1

I share full Code:

<script src="{LINK}code.highcharts.com/stock/highstock.js"></script>
<script src="{LINK}code.highcharts.com/stock/modules/exporting.js"></script>
<script src="{LINK}code.highcharts.com/modules/accessibility.js"></script>

<div id="container"></div>

<style>
  #container {
    height: 500px; /* Adjust height as needed */
    min-width: 310px;
  }
</style>

<script>
  (async () => {
  try {
    // Log the current URL for debugging
    const currentUrl = window.location.href;
    console.log("Current URL:", currentUrl);

    // Extract the item code part before the dash (e.g., "0001", "0002")
    const match = currentUrl.match(/\/item\/(\d{4})-\d+/);  
    console.log("Match result:", match);

    // Check if the match was successful
    if (!match) {
      console.error("No valid identifier found in the URL. Ensure the URL format is '/item/XXXX-YYYY'.");
      return;
    }

    const itemCode = match[1]; // Extract itemCode (e.g., "0001")
    console.log("Extracted itemCode:", itemCode); 

    // Define the Google Sheets CSV URL
    const sheetUrl = 'https://docs.google.com/spreadsheets/d/1cLVBbZ4ikg5TU5oGK2oPHq3yC2iX1kYxD3e-gJ4qbh8/export?format=csv&gid=1430848937';

    // Dynamically determine column indices based on itemCode
    let btcIndex, rapIndex, usdIndex, volumeIndex;
    switch (itemCode) {
      case '0001':
        btcIndex = 4; rapIndex = 5; usdIndex = 6; volumeIndex = 7;
        break;
      case '0002':
        btcIndex = 8; rapIndex = 9; usdIndex = 10; volumeIndex = 11;
        break;
      case '0003':
        btcIndex = 12; rapIndex = 13; usdIndex = 14; volumeIndex = 15;
        break;
      case '0004':
        btcIndex = 16; rapIndex = 17; usdIndex = 18; volumeIndex = 19;
        break;
      default:
        console.error("No valid identifier found for item:", itemCode);
        return;
    }

    // Fetch the CSV data from Google Sheets
    const response = await fetch(sheetUrl);
    const csvText = await response.text();
    const rows = csvText.split('\n').map(row => row.split(','));

    // Prepare data arrays
    const btcData = [];
    const rapData = [];
    const usdData = [];
    const volumeData = [];

    // Process rows from CSV and populate the data arrays
    rows.slice(4).forEach(row => {
      const timestamp = parseInt(row[3]?.trim());

      const btcValue = parseFloat(row[btcIndex]?.trim());
      const rapValue = parseFloat(row[rapIndex]?.trim());
      const usdValue = parseFloat(row[usdIndex]?.trim());
      const volumeValue = parseFloat(row[volumeIndex]?.trim());

      if (!isNaN(timestamp) && !isNaN(btcValue) && !isNaN(rapValue) && !isNaN(usdValue)) {
        btcData.push([timestamp, btcValue]);
        rapData.push([timestamp, rapValue]);
        usdData.push([timestamp, usdValue]);
        volumeData.push([timestamp, volumeValue]);
      }
    });

      // Log the final arrays to verify the data
      console.log('btcData:', btcData);
      console.log('rapData:', rapData);
      console.log('usdData:', usdData);
      console.log('volumeData:', volumeData);

      // Create the Highcharts chart with the fetched data
      Highcharts.stockChart('container', {
        accessibility: {
          typeDescription: 'Stock chart showing Bitcoin, RAP, USD values, and Volume over time.'
        },

        chart: {
          backgroundColor: {
            linearGradient: [0, 0, 0, 500], // Gradient from top to bottom
            stops: [
              [0, '#000000'],   // Start color (black)
              [1, '#434343']    // End color (dark gray)
            ]
          }
        },

        title: {
          text: '',
          style: {
            color: '#fff' // Set title text color to white
          }
        },

        rangeSelector: {
          selected: 3,
          buttons: [{
            type: 'month',
            count: 3,
            text: '3m',
            title: 'View 3 months'
          }, {
            type: 'month',
            count: 6,
            text: '6m',
            title: 'View 6 months'
          }, {
            type: 'ytd',
            text: 'YTD',
            title: 'View year to date'
          }, {
            type: 'year',
            count: 1,
            text: '1y',
            title: 'View 1 year'
          }, {
            type: 'all',
            text: 'All',
            title: 'View all'
          }],
          labelStyle: {
            color: '#fff' // Set range selector labels color to white
          }
        },

        xAxis: {
          type: 'datetime', // Set to datetime to interpret the timestamps correctly
          labels: {
            style: {
              color: '#fff' // Set x-axis labels color to white
            },
            formatter: function () {
              return Highcharts.dateFormat('%b %e, %Y', this.value); // Format as "Mar 1, 2025"
            }
          },
          lineColor: '#fff' // Set x-axis line color to white
        },

        yAxis: [{
          labels: {
            style: {
              color: '#fff' // Set y-axis labels color to white
            }
          },
          title: {
            text: 'Price',
            style: {
              color: '#fff' // Set y-axis title color to white
            }
          },
          gridLineColor: '#444' // Optional: Change grid line color for better visibility
        }, {
          labels: {
            style: {
              color: '#fff' // Set y-axis labels color to white
            }
          },
          title: {
            text: 'Volume',
            style: {
              color: '#fff' // Set y-axis title color to white
            }
          },
          top: '88%',    // Set the top to start just below the main chart
          height: '12%', // Decrease the height of the volume chart
          offset: 0,
          gridLineColor: '#444' // Optional: Change grid line color for better visibility
        }],

        tooltip: {
          split: true,
          backgroundColor: 'rgba(0, 0, 0, 0.75)', // Set tooltip background to slightly transparent black
          style: {
            color: '#fff' // Set tooltip text color to white
          },
          pointFormatter: function () {
            if (this.series.name === 'Volume') {
              // For volume series, display "Units"
              return `<b>${Highcharts.dateFormat('%b %e, %Y', this.x)}</b><br/>
                      <b>${this.series.name}:</b> ${this.y} Units`;
            } else if (this.series.name === 'Avg Price Sold' || this.series.name === 'RAP Value') {
              // For Avg Price Sold and RAP Value, display "ETH"
              return `<b>${Highcharts.dateFormat('%b %e, %Y', this.x)}</b><br/>
                      <b>${this.series.name}:</b> ${this.y.toFixed(2)} ETH`;
            } else {
              // For other series (USD Value), display "$"
              return `<b>${Highcharts.dateFormat('%b %e, %Y', this.x)}</b><br/>
                      <b>${this.series.name}:</b> $${this.y.toFixed(2)}`;
            }
          }
        },

        legend: {
          enabled: true,
          layout: 'horizontal',
          align: 'center',
          verticalAlign: 'bottom',
          itemStyle: {
            color: '#fff' // Set legend item color to white
          },
          itemHoverStyle: {
            color: '#ffbf00' // Optional: Change color of legend item on hover
          }
        },

        series: [{
          name: 'Avg Price Sold',
          color: '#ffbf00',
          data: btcData,
          id: 'btcSeries',
          tooltip: {
            valueDecimals: 2,
            valueSuffix: ' ETH'
          }
        }, {
          name: 'RAP Value',
          color: '#0071A7',
          data: rapData,
          id: 'rapSeries',
          tooltip: {
            valueDecimals: 2,
            valueSuffix: ' ETH'
          }
        }, {
          name: 'USD Value',
          color: '#FF5733',
          data: usdData,
          id: 'usdSeries',
          visible: false, // Make this series initially hidden
          tooltip: {
            valueDecimals: 2,
            valuePrefix: '$'
          }
        }, {
          type: 'column',
          name: 'Volume',
          data: volumeData,
          yAxis: 1,
          tooltip: {
            valueDecimals: 0,
            valueSuffix: ' Units'
          }
        }]
      });

    } catch (error) {
      console.error("Error fetching or processing data:", error);
    }
  })();
</script>