callbacks

PHOTO EMBED

Mon Jun 17 2024 11:39:55 GMT+0000 (Coordinated Universal Time)

Saved by @davidmchale #callback

const getSelectValue = (callback) => {
  const options = getElement("#city-select");

  options.addEventListener("change", function (e) {
    const value = e.target.value;
    // pass the value into the callback function we can use later
    callback(value); // this value needs to be passed into the function where we are using the getSelectValue function ie  getSelectValue(value)
  });
};




// app function
const init = () => {
  // populate the DOM with the cities data on load
  const selectDOM = getElement("#city-select");
  populateDOM(cities, selectDOM);

  let selectedCity = ""; // this gets updated with the function below

  // need to run the callback here
  // get the value and assign it to a variable outside the function
  getSelectValue((value) => {
    selectedCity = value; // Assign the value to selectedCity
    //  // Log the selected city
    if (selectedCity !== "") {
      const container = getElement(".container h3");
      container.textContent = selectedCity;
    }
  });
};

window.addEventListener("DOMContentLoaded", init);

content_copyCOPY