JSFiddle - React, Tailwind, and code Playground
by Balkanlii
HTML
<head>
<meta charset="UTF-8">
</head>
<table>
<tr>
<td>
<select id = "locationList" onchange="locationListChanged()" style="width:115px;">
<option value = "Toronto,CA">Toronto, CA</option>
<option value = "Montreal,CA">Montreal, CA</option>
<option value = "Laval,CA">Laval, CA</option>
<option value = "Halifax,CA">Halifax, CA</option>
<option value = "Berlin,DE">Berlin, DE</option>
<option value = "Melbourne,AU">Melbourne, AU</option>
<option value = "Auckland,NZ">Auckland, NZ</option>
<option value = "São Paulo,NZ">São Paulo, NZ</option>
<option value = "Amsterdam,NL">Amsterdam, NL</option>
<option value = "Izmir,Turkey">Izmir, TUR</option>
</select>
</td>
</tr>
<tr style="text-align:center;">
<td>
<div>
<div id="w-location" style="display:none;"></div>
<p id="w-temp"></p>
<h3 class="text-dark" id="w-desc" style="display:none;"></h3>
<img id="w-icon" style="margin-top:-25px;"/>
</div>
</td>
</tr>
</table>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
JavaScript
class Weather {
constructor(city, country) {
this.apiKey = '75eaf60570f8bf64f5d503fdf187dd92'
this.city = city;
this.country = country;
}
async getWeather() {
var response = await fetch(`https://api.openweathermap.org/data/2.5/weather?APPID=${this.apiKey}&q=${this.city},${this.country}.json`)
var responseData = await response.json();
return responseData;
}
}
class UI {
constructor() {
this.location = document.getElementById('w-location');
this.desc = document.getElementById('w-desc');
this.icon = document.getElementById('w-icon');
this.temp = document.getElementById('w-temp');
}
showRes(weather) {
weather.weather.map((x) => {
this.desc.textContent = x.description;
this.icon.setAttribute('src', `https://openweathermap.org/img/w/${x.icon}.png`);
})
this.location.textContent = `${weather.name}, ${weather.sys.country}`;
this.temp.textContent = `${parseInt(weather.main.temp - 273.15,10)} °C`;
}
}
function locationListChanged(){
findWeatherInfo();
}
function findWeatherInfo(){
var ui = new UI;
var e = document.getElementById("locationList");
var val = e.options[e.selectedIndex].value;
var weather = new Weather(val.split(',')[0], val.split(',')[1]);
weather.getWeather()
.then(res => {
ui.showRes(res);
})
}
$.ajax({
url: "https://geoip-db.com/jsonp",
jsonpCallback: "callback",
dataType: "jsonp",
success: function(location) { console.log(location);
document.getElementById('locationList').value = location.city + ',' + location.country_code;
}
});
document.addEventListener('DOMContentLoaded', getWeather)
var ui = new UI;
var e = document.getElementById("locationList");
var val = e.options[e.selectedIndex].value;
var weather = new Weather(val.split(',')[0], val.split(',')[1])
function getWeather() {
weather.getWeather()
.then(res => {
ui.showRes(res);
})
}