Skip to content

Instantly share code, notes, and snippets.

@marcoranieri
Created July 13, 2019 10:50
Show Gist options
  • Save marcoranieri/57543b446751f4b51c7740a84ac74d5b to your computer and use it in GitHub Desktop.
Save marcoranieri/57543b446751f4b51c7740a84ac74d5b to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Weather</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="css/style.css">
<link rel="stylesheet" href="node_modules/select2/dist/css/select2.css">
</head>
<body>
<form action="">
<label for="city">City</label>
<input id="search" placeholder="to search..." type="text" name="city">
<input id="submit" type="submit" value="Submit">
</form>
<hr>
<p>or select a City from the list:</p>
<select id="city-input" class="select2">
<option value=""></option>
</select>
<hr>
<p>or get your Coordinates here:</p>
<button id="coordBtn">Get Coords</button> <span id="coordText">...</span>
<hr>
<h1>Weather in <span id="city-name">...</span></h1>
<div id="card" style="display:none">
<h3 id="date">Friday, November 2, 6PM</h3>
<p id="description">Description here</p>
<img id="iconImg" src="http://openweathermap.org/img/w/11d.png">
<h3 id="temp">8°C</h3>
</div>
<script src="main.js"></script>
</body>
</html>
const API_KEY = __INSERT YOUR API KEY HERE__ ( https://openweathermap.org/appid )
const form = document.querySelector("form")
const searchField = document.querySelector("#search")
const url = (value) => `http://api.openweathermap.org/data/2.5/weather?q=${value}&units=metric&appid=${API_KEY}`
const handleData = (data) => {
// filtering & collecting data
const description = data.weather[0].description
const weather = data.weather[0].main
const icon = data.weather[0].icon
const temp = data.main.temp
const name = data.name
const cityNameSpan = document.querySelector("#city-name")
cityNameSpan.innerText = name
const descriptionElement = document.querySelector("#description")
descriptionElement.innerText = description
// display the CARD
const card = document.querySelector("#card")
card.style.display = "block"
card.style.border = "2px solid darkgrey"
card.style.padding = "20px"
}
form.addEventListener("submit", (e) => {
// Prevent the POST action
e.preventDefault()
const value = searchField.value
// Fetching URL
fetch(url(value)) // pending Promise
.then(response => response.json()) // resolved Promise
.then(data => handleData(data)) // JS Obj - API
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment