I have two buttons to toggle between cities for a weather API.
When I assign the variable to be determined by button click:
TButton.addEventListener("click", TWeather);
function TWeather(){
outputDiv.style.display = "block";
const buttonCity = "Toronto";
};
the URL for the API won't recognize it.
const url = "https://api.openweathermap.org/data/2.5/weather?q=" + buttonCity + "&appid=" + myAPIkey + "&units=metric";
It works if I set the variable outside of the button function.
The problem is that you are defining the buttonCity variable in the TWeather function so that variable is only available in the scope of that function. Please read the following: https://www.w3schools.com/js/js_scope.asp
You will have to assign this variable where it is accessible to the other function as well.
Example:
let currentCity = '';
TButton.addEventListener("click", TWeather);
function TWeather(){
outputDiv.style.display = "block";
currentCity = "Toronto";
};
And then API CALL:
const url = "https://api.openweathermap.org/data/2.5/weather?q=" + currentCity + "&appid=" + myAPIkey + "&units=metric";
I think that const is a local variable not a global one. Define your variable after the addEventListener outside the function and give it a try.
You did not specify what you wanted to do with the URL so I just did a console.log.
Here I create a object and add some properties including some functions to add the event handler. I also added the target city to each button as a data attribute, then pulled that out within the event handler.
This is a bit overkill perhaps but does illustrate some ways to avoid global variables and make it so you can add more buttons to the HTML without any code changes.
var myapp = {
url: {
base: "https://api.openweathermap.org/data/2.5/weather?q=",
api: "&appid=",
unit: "&units=metric"
},
apiKey = "key",
baseSelector:".weather-toggle",
buttons: {},
init: function() {
const app = this;
this.buttons = document.querySelectorAll(this.baseSelector);
this.buttons.forEach(function(button, index, buttons) {
button.addEventListener("click", this.toggleWeather, false);
},this);
},
toggleWeather: function(event) {
const targetCity = event.target.dataset.targetCity;
const url = myapp.url.base + targetCity + myapp.url.api + myapp.apiKey + myapp.url.unit;
console.log(url);
}
};
myapp.init.apply(myapp);
<button class="weather-toggle" type="button" data-target-city="Toronto">Toronto</button>
<button class="weather-toggle" type="button" data-target-city="NewYork">New York City</button>
<button class="weather-toggle" type="button" data-target-city="Boston">Boston</button>