skip to Main Content

I have very little experience with javascript and this is the only issue with the file that I need to resolve. I am proficcent in python. My python script saves a json file which contains:

["May 28n04 PM ET", "May 28n06 PM ET", "May 28n08 PM ET", "May 28n10 PM ET", "May 29n12 AM ET", "May 29n02 AM ET", "May 29n06 AM ET", "May 29n08 AM ET", "May 29n10 AM ET", "May 29n12 PM ET", "May 29n02 PM ET", "May 29n06 PM ET", "May 29n10 PM ET", "May 30n12 AM ET"]

What I want to do in my javascript that someone else wrote for me is replace some of the the time equal to the first value of that json list.

  //MAP STUFF

  // Array of objects containing button data
  // Array of objects containing button data

  document.addEventListener("DOMContentLoaded", function () {
      const test1 = 'hi'
      async function fetchFirstItemFromJSON(filePath) {
        try {
          const response = await fetch(filePath); // Fetch the JSON file
          const data = await response.json(); // Parse the JSON data
      
          // Set the first item in the list to a variable
          const firstItem = data[0];
      
          console.log(firstItem); // Output the first item
      
          // Continue with any further processing using the first item...
        } catch (error) {
          console.log('Error reading JSON file:', error);
        }
      }

      fetchFirstItemFromJSON('C:UserskevinDocumentsAerocast V1.1assetstimes.json'); // Replace 'path/to/your/file.json' with the actual path to your JSON file
      const buttons = [{
              htmlFile: 'interactive_2.html',
              pngFile: 'fctime_2.png',
              time: firstItem,
          },
          {
              htmlFile: 'interactive_4.html',
              pngFile: 'fctime_4.png',
              time: "20/05n20:00",
          },
          {
              htmlFile: 'interactive_6.html',
              pngFile: 'fctime_6.png',
              time: "20/05n22:00",
          },
          {
              htmlFile: 'interactive_8.html',
              pngFile: 'fctime_8.png',
              time: "21/05n00:00",
          },
          {
              htmlFile: 'interactive_10.html',
              pngFile: 'fctime_10.png',
              time: "21/05n02:00",
          },
          {
              htmlFile: 'interactive_12.html',
              pngFile: 'fctime_12.png',
              time: "21/05n06:00",
          },
          {
              htmlFile: 'interactive_14.html',
              pngFile: 'fctime_14.png',
              time: "21/05n08:00",
          },
          {
              htmlFile: 'interactive_16.html',
              pngFile: 'fctime_16.png',
              time: "21/05n10:00",
          },
          {
              htmlFile: 'interactive_18.html',
              pngFile: 'fctime_18.png',
              time: "21/05n12:00",
          },
          {
              htmlFile: 'interactive_24.html',
              pngFile: 'fctime_24.png',
              time: "21/05n14:00",
          },
          {
              htmlFile: 'interactive_28.html',
              pngFile: 'fctime_28.png',
              time: "21/05n16:00",
          },
          {
              htmlFile: 'interactive_32.html',
              pngFile: 'fctime_32.png',
              time: "21/05n22:00",
          },
          {
              htmlFile: 'interactive_36.html',
              pngFile: 'fctime_36.png',
              time: "22/05n00:00",
          },
      ];
      const buttonContainer = document.getElementById("buttonContainer");
      const mapDetails = document.getElementById("mapDetails");
      const mapDisplay = document.getElementById("mapDisplay");
      const mapRange = document.getElementById("mapRange");
      const previousButton = document.getElementById("previousButton");
      const nextButton = document.getElementById("nextButton");
      let activeButtonIndex = 0;

      //Set the range max value to the number of buttons
      mapRange.max = buttons.length - 1;

      // Function to change the active button
      function setActiveButton(index) {
          const buttons = buttonContainer.getElementsByClassName("mapButton");
          for (let i = 0; i < buttons.length; i++) {
              buttons[i].classList.remove("activeMapButton");
          }
          buttons[index].classList.add("activeMapButton");
          activeButtonIndex = index;
      }

      // Function to change the map details and display
      function changeMap(button) {
          mapDetails.src = `./assets/${button.pngFile}`;
          mapDisplay.src = `./assets/${button.htmlFile}`;
      }

      // Function to handle button clicks
      function handleButtonClick(index) {
          if (index != +activeButtonIndex) {
              setActiveButton(index);
              changeMap(buttons[index]);
              mapRange.value = index;
          }
      }

      // Function to handle previous button click
      function handlePreviousButtonClick() {
          if (activeButtonIndex > 0) {
              handleButtonClick(+activeButtonIndex - 1);
          }
      }

      // Function to handle next button click
      function handleNextButtonClick() {
          if (+activeButtonIndex < buttons.length - 1) {
              handleButtonClick(+activeButtonIndex + 1);
          }
      }

      // Create buttons based on the array
      buttons.forEach((button, index) => {
          const buttonElement = document.createElement("button");
          const prevNextButtons = document.querySelector(".nextprev");
          buttonElement.innerHTML = `${button.time.replace(/n/g, "<br>")}`;
          buttonElement.classList.add("mapButton");
          buttonElement.addEventListener("click", () => handleButtonClick(index));
          buttonContainer.insertBefore(buttonElement, prevNextButtons);
      });

      // Add event listeners to previous and next buttons
      previousButton.addEventListener("click", handlePreviousButtonClick);
      nextButton.addEventListener("click", handleNextButtonClick);

      // Add event listener to range input
      mapRange.addEventListener("input", () => {
          handleButtonClick(mapRange.value);
      });
      // Set the initial active button and map display
      setActiveButton(activeButtonIndex);
      changeMap(buttons[activeButtonIndex]);


  });

  // Update sidebar with content from Markdown files
  updateSidebarContent('./assets/information.md', 'informationContent');
  updateSidebarContent('./assets/extended_outlook.md', 'extendedOutlookContent');

This was my attempt at trying to solve this problem. When I replace my first time with time: test1
it works, but once I replace test1 with firstItem it breaks. I just want this simple error resolved. Thank you!

This was my first attempt

      async function fetchFirstItemFromJSON(filePath) {
        try {
          const response = await fetch(filePath); // Fetch the JSON file
          const data = await response.json(); // Parse the JSON data
      
          // Set the first item in the list to a variable
          const firstItem = data[0];
      
          console.log(firstItem); // Output the first item
      
          // Continue with any further processing using the first item...
        } catch (error) {
          console.log('Error reading JSON file:', error);
        }
      }

      fetchFirstItemFromJSON('C:UserskevinDocumentsAerocast V1.1assetstimes.json'); // Replace 'path/to/your/file.json' with the actual path to your JSON file

2

Answers


  1. You defined the variable firstItem inside fetchFirstItemFromJSON. So, you can’t use its value outside the function fetchFirstItemFromJSON.

    What you need to do is define the variable firstItem outside the function fetchFirstItemFromJSON then assign the value inside the function. Like this:

    const test1 = 'hi';
    // ----define here----
    var firstItem = "";
          async function fetchFirstItemFromJSON(filePath) {
            try {
              const response = await fetch(filePath); // Fetch the JSON file
              const data = await response.json(); // Parse the JSON data
          
              // Set the first item in the list to a variable
              firstItem = data[0];
          
              console.log(firstItem); // Output the first item
          
              // Continue with any further processing using the first item...
            } catch (error) {
              console.log('Error reading JSON file:', error);
            }
          }
    fetchFirstItemFromJSON('C:UserskevinDocumentsAerocast V1.1assetstimes.json') // Replace 'path/to/your/file.json' with the actual path to your JSON file
    .then(() => {
          const buttons = [{
                  htmlFile: 'interactive_2.html',
                  pngFile: 'fctime_2.png',
                  time: firstItem,
              },
              {
                  htmlFile: 'interactive_4.html',
                  pngFile: 'fctime_4.png',
                  time: "20/05n20:00",
              },
              {
                  htmlFile: 'interactive_6.html',
                  pngFile: 'fctime_6.png',
                  time: "20/05n22:00",
              },
              {
                  htmlFile: 'interactive_8.html',
                  pngFile: 'fctime_8.png',
                  time: "21/05n00:00",
              },
              {
                  htmlFile: 'interactive_10.html',
                  pngFile: 'fctime_10.png',
                  time: "21/05n02:00",
              },
              {
                  htmlFile: 'interactive_12.html',
                  pngFile: 'fctime_12.png',
                  time: "21/05n06:00",
              },
              {
                  htmlFile: 'interactive_14.html',
                  pngFile: 'fctime_14.png',
                  time: "21/05n08:00",
              },
              {
                  htmlFile: 'interactive_16.html',
                  pngFile: 'fctime_16.png',
                  time: "21/05n10:00",
              },
              {
                  htmlFile: 'interactive_18.html',
                  pngFile: 'fctime_18.png',
                  time: "21/05n12:00",
              },
              {
                  htmlFile: 'interactive_24.html',
                  pngFile: 'fctime_24.png',
                  time: "21/05n14:00",
              },
              {
                  htmlFile: 'interactive_28.html',
                  pngFile: 'fctime_28.png',
                  time: "21/05n16:00",
              },
              {
                  htmlFile: 'interactive_32.html',
                  pngFile: 'fctime_32.png',
                  time: "21/05n22:00",
              },
              {
                  htmlFile: 'interactive_36.html',
                  pngFile: 'fctime_36.png',
                  time: "22/05n00:00",
              },
          ];
          const buttonContainer = document.getElementById("buttonContainer");
          const mapDetails = document.getElementById("mapDetails");
          const mapDisplay = document.getElementById("mapDisplay");
          const mapRange = document.getElementById("mapRange");
          const previousButton = document.getElementById("previousButton");
          const nextButton = document.getElementById("nextButton");
          let activeButtonIndex = 0;
    
          //Set the range max value to the number of buttons
          mapRange.max = buttons.length - 1;
    
          // Function to change the active button
          function setActiveButton(index) {
              const buttons = buttonContainer.getElementsByClassName("mapButton");
              for (let i = 0; i < buttons.length; i++) {
                  buttons[i].classList.remove("activeMapButton");
              }
              buttons[index].classList.add("activeMapButton");
              activeButtonIndex = index;
          }
    
          // Function to change the map details and display
          function changeMap(button) {
              mapDetails.src = `./assets/${button.pngFile}`;
              mapDisplay.src = `./assets/${button.htmlFile}`;
          }
    
          // Function to handle button clicks
          function handleButtonClick(index) {
              if (index != +activeButtonIndex) {
                  setActiveButton(index);
                  changeMap(buttons[index]);
                  mapRange.value = index;
              }
          }
    
          // Function to handle previous button click
          function handlePreviousButtonClick() {
              if (activeButtonIndex > 0) {
                  handleButtonClick(+activeButtonIndex - 1);
              }
          }
    
          // Function to handle next button click
          function handleNextButtonClick() {
              if (+activeButtonIndex < buttons.length - 1) {
                  handleButtonClick(+activeButtonIndex + 1);
              }
          }
    
          // Create buttons based on the array
          buttons.forEach((button, index) => {
              const buttonElement = document.createElement("button");
              const prevNextButtons = document.querySelector(".nextprev");
              buttonElement.innerHTML = `${button.time.replace(/n/g, "<br>")}`;
              buttonElement.classList.add("mapButton");
              buttonElement.addEventListener("click", () => handleButtonClick(index));
              buttonContainer.insertBefore(buttonElement, prevNextButtons);
          });
    
          // Add event listeners to previous and next buttons
          previousButton.addEventListener("click", handlePreviousButtonClick);
          nextButton.addEventListener("click", handleNextButtonClick);
    
          // Add event listener to range input
          mapRange.addEventListener("input", () => {
              handleButtonClick(mapRange.value);
          });
          // Set the initial active button and map display
          setActiveButton(activeButtonIndex);
          changeMap(buttons[activeButtonIndex]);
    });
    
    Login or Signup to reply.
  2. You cannot pass variables across functions without defining then globally or passing the variables as function arguments. Try this.

    async function fetchFirstItemFromJSON(filePath) {
        try {
            ....
            return firstItem;
        } catch (error) {
            ....
            return null;
        }
      }
    
    var firstItem = await fetchFirstItemFromJSON('C:UserskevinDocumentsAerocast V1.1assetstimes.json'); // Replace 'path/to/your/file.json' with the actual path to your JSON file
      
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search