Javascript Weather App
HTML File
Here, we are creating a input to search a city and an main section to display the weather.
<form id="form"> <input type="text" id="search" placeholder="Search By Location" autocomplete="off"> </form> <main id="main"> </main>JavaScript File Let's first declare few variables and access the HTML elements: It's weather api from openweathermap. You can generate yours from this website: https://openweathermap.org
const apiKey = "d102ce6f8a7f8c61a416505fdeb98697"; const main = document. getElementById( 'main'); const form = document. getElementById( 'form' ); const search = document. getElementById( 'search' ); const url = (city)=> 'https://api.openweathermap.org/data/2.5/weather? q=${city}&appid=d102ce6f8a7f8c61a416505fdeb98697';Let's fetch the weather as per the city name:
async function getWeatherBylLocation(city){ const resp = await fetch(url(city), { origin: "cros" }); const respData = await resp.json(); addWeatherToPage(respData); }This is the function to show the weather and icons as per the weather:
function addweatherToPage(data){ const temp = Ktoc(data.main.temp); const weather = document.createElement('div') weather. classList.add('weather'); weather.innerHTHL = ' <h2> <img src="https://openweathermap.org/img/wn/${ data.weather[0].icon}@2x.png" /> ${temp}*C <img src="https://openweathermap.org/img/wn/${ data.weather[0].icon}@2x.png" /> </h2> <small>${data.weather[0].main}</small>'; // cleanup matin.innerHTHL= ""; main.appendChild(weather); };Here, we are the converting the temperature into celsius and lastly adding the submit event to the search input.
function Ktoc(K){ return Math.floor(K - 273.15); } form.addEventListener('submit',(e) =>{ e.preventDefault(); const city = search.value; if(city){ getWeatherByLocation(city) } });
No comments:
New comments are not allowed.