Skip to content

Instantly share code, notes, and snippets.

@AVGP
Last active December 30, 2016 11:20
Show Gist options
  • Save AVGP/b4cd75e74786c3034445401844c0efdc to your computer and use it in GitHub Desktop.
Save AVGP/b4cd75e74786c3034445401844c0efdc to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
</head>
<body>
<template id="weather-info">
<style>
:host {
display: inline-block;
padding: 1em;
min-width: 20em;
border: 1px solid grey;
}
img {
float: left;
}
h2 {
margin-top: 0;
line-height: 50px;
}
p {
clear: both;
font-weight: bold;
font-size: 1.5em;
}
</style>
<img>
<h2>Weather in <span id="city"></span>:</h2>
<p id="weather"></p>
</template>
<script>
class WeatherInfo extends HTMLElement {
constructor() {
super()
let doc = (document.currentScript ? document.currentScript.ownerDocument : document)
this._tpl = doc.getElementById('weather-info').content
this._shadow = this.attachShadow({mode: 'open'})
}
get city() {
return this.getAttribute('city')
}
set city(value) {
this.setAttribute('city', value)
this.update()
}
get isMetric() {
return this.hasAttribute('metric')
}
set isMetric(value) {
if(value) this.setAttribute('metric', '')
else this.removeAttribute('metric')
this.update()
}
getWeather(city, isMetric) {
let units = (isMetric ? 'metric' : 'imperial')
fetch(`http://api.openweathermap.org/data/2.5/weather?q=${city}&units=${units}&appid=6fb16872c800649a6f7a568cccda7475`)
.then((result) => { return result.json() })
.then((result) => {
this._shadow.getElementById('city').textContent = city
this._shadow.getElementById('weather').textContent = `${result.main.temp} °${isMetric ? 'C' : 'F'} - ${result.weather[0].main}`
this._shadow.querySelector('img').src = `http://openweathermap.org/img/w/${result.weather[0].icon}.png`
})
}
update() {
let city = this.getAttribute('city')
let isMetric = this.hasAttribute('metric')
this.getWeather(city, isMetric)
}
connectedCallback() {
let content = this._tpl.cloneNode(true)
this._shadow.appendChild(content)
let city = this.getAttribute('city')
let isMetric = this.hasAttribute('metric')
this.getWeather(city, isMetric)
}
attributeChangedCallback(name, oldValue, newValue) {
switch(name.toLowerCase()) {
case 'city':
this.city = newValue
this.update()
break
case 'metric':
this.isMetric = newValue
this.update()
break
}
}
}
window.customElements.define('weather-info', WeatherInfo)
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment