HTML preprocessors can make writing HTML more powerful or convenient. For instance, Markdown is designed to be easier to write and read for text documents and you could write a loop in Pug.
In CodePen, whatever you write in the HTML editor is what goes within the <body>
tags in a basic HTML5 template. So you don't have access to higher-up elements like the <html>
tag. If you want to add classes there that can affect the whole document, this is the place to do it.
In CodePen, whatever you write in the HTML editor is what goes within the <body>
tags in a basic HTML5 template. If you need things in the <head>
of the document, put that code here.
The resource you are linking to is using the 'http' protocol, which may not work when the browser is using https.
CSS preprocessors help make authoring CSS easier. All of them offer things like variables and mixins to provide convenient abstractions.
It's a common practice to apply CSS to a page that styles elements such that they are consistent across all browsers. We offer two of the most popular choices: normalize.css and a reset. Or, choose Neither and nothing will be applied.
To get the best cross-browser support, it is a common practice to apply vendor prefixes to CSS properties and values that require them to work. For instance -webkit-
or -moz-
.
We offer two popular choices: Autoprefixer (which processes your CSS server-side) and -prefix-free (which applies prefixes via a script, client-side).
Any URLs added here will be added as <link>
s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.
You can apply CSS to your Pen from any stylesheet on the web. Just put a URL to it here and we'll apply it, in the order you have them, before the CSS in the Pen itself.
You can also link to another Pen here (use the .css
URL Extension) and we'll pull the CSS from that Pen and include it. If it's using a matching preprocessor, use the appropriate URL Extension and we'll combine the code before preprocessing, so you can use the linked Pen as a true dependency.
JavaScript preprocessors can help make authoring JavaScript easier and more convenient.
Babel includes JSX processing.
Any URL's added here will be added as <script>
s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.
You can apply a script from anywhere on the web to your Pen. Just put a URL to it here and we'll add it, in the order you have them, before the JavaScript in the Pen itself.
If the script you link to has the file extension of a preprocessor, we'll attempt to process it before applying.
You can also link to another Pen here, and we'll pull the JavaScript from that Pen and include it. If it's using a matching preprocessor, we'll combine the code before preprocessing, so you can use the linked Pen as a true dependency.
Search for and use JavaScript packages from npm here. By selecting a package, an import
statement will be added to the top of the JavaScript editor for this package.
Using packages here is powered by esm.sh, which makes packages from npm not only available on a CDN, but prepares them for native JavaScript ESM usage.
All packages are different, so refer to their docs for how they work.
If you're using React / ReactDOM, make sure to turn on Babel for the JSX processing.
If active, Pens will autosave every 30 seconds after being saved once.
If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.
If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.
Visit your global Editor Settings.
<svg style="display:none;" version="1.0" xmlns="http://www.w3.org/2000/svg">
<symbol id="CC_by_sign" viewbox="5.5 -3.5 64 64">
<circle fill="currentColor" cx="37.637" cy="28.806" r="28.276"/>
<path d="M37.443-3.5c8.988,0,16.57,3.085,22.742,9.257C66.393,11.967,69.5,19.548,69.5,28.5c0,8.991-3.049,16.476-9.145,22.456
C53.879,57.319,46.242,60.5,37.443,60.5c-8.649,0-16.153-3.144-22.514-9.43C8.644,44.784,5.5,37.262,5.5,28.5
c0-8.761,3.144-16.342,9.429-22.742C21.101-0.415,28.604-3.5,37.443-3.5z M37.557,2.272c-7.276,0-13.428,2.553-18.457,7.657
c-5.22,5.334-7.829,11.525-7.829,18.572c0,7.086,2.59,13.22,7.77,18.398c5.181,5.182,11.352,7.771,18.514,7.771
c7.123,0,13.334-2.607,18.629-7.828c5.029-4.838,7.543-10.952,7.543-18.343c0-7.276-2.553-13.465-7.656-18.571
C50.967,4.824,44.795,2.272,37.557,2.272z M46.129,20.557v13.085h-3.656v15.542h-9.944V33.643h-3.656V20.557
c0-0.572,0.2-1.057,0.599-1.457c0.401-0.399,0.887-0.6,1.457-0.6h13.144c0.533,0,1.01,0.2,1.428,0.6
C45.918,19.5,46.129,19.986,46.129,20.557z M33.042,12.329c0-3.008,1.485-4.514,4.458-4.514s4.457,1.504,4.457,4.514
c0,2.971-1.486,4.457-4.457,4.457S33.042,15.3,33.042,12.329z"/>
</symbol>
</svg>
<main class="main">
<h1 class='header'>Your local weather conditions.</h1>
<button class="about__button" aria-label="Information about this page">i</button>
<div class="geo-details">
<p class="geo-details__time"></p>
<p class="geo-details__date"></p>
<p class="geo-details__place"></p>
</div>
<div class="weather">
<span class="weather__sky"></span>
<div class="weather__temp font--bigger"></div>
<fieldset class="radio__list">
<input class="radio__item radio__item--fahrenheit" type="radio" id="scaleFahrenheit" name="scaleSwitch" tabindex="-1" aria-checked="true" aria-label="Set scale to Fahrenheit"/>
<label class="label__item label__item--fahrenheit vivid font--bigger" for="scaleFahrenheit" tabindex="0" aria-labelledby="scaleFahrenheit">F</label>
<span class="vague font--bigger">/</span>
<input class="radio__item radio__item--celsius" type="radio" id="scaleCelsius" name="scaleSwitch" tabindex="-1" aria-checked="false" aria-label="Set scale to Celsius"/>
<label class="label__item label__item--celsius font--bigger" for="scaleCelsius" tabindex="0" aria-labelledby="scaleCelsius">C</label>
</fieldset>
</div>
</main>
<div class="about modal closed">
<button class="about__button--close-modal" aria-label="Close">X</button>
<p>It's an approach to a "Local weather app" from <a href="https://www.freecodecamp.org/challenges/show-the-local-weather">FreeCodeCamp</a> curriculum.</p>
<p>User story:</p>
<ul>
<li>I can see the weather in my current location.</li>
<li>I can see a different icon or background image (e.g. snowy mountain, hot desert) depending on the weather.</li>
<li>I can push a button to toggle between Fahrenheit and Celsius.</li>
</ul>
</div>
<div class="copyright">
<!-- <svg class="copyright__sign">
<use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#CC_by_sign"></use>
</svg>-->
<p class="copyright__text"></p>
</div>
root {
--text-color: #fff;
--bg-color: #fff;
}
.main {
border-radius: 5px;
color: var(--text-color);
background-color: var(--bg-color);
display: inline-block;
margin-left: 10vw;
margin-top: 15vh;
opacity: 0.8;
padding: 1rem;
position: relative;
text-transform: uppercase;
}
.header {
visibility: hidden;
margin: 0;
padding: 0;
line-height: 0;
width: 0;
}
.about {
background-color: var(--bg-color);
border: 2px solid var(--text-color);
border-radius: 5px;
color: var(--text-color);
display: block;
padding: 1rem;
padding-top: 1.5rem;
position: relative;
}
.modal {
left: 0;
margin-top: 15%;
margin-left: 10%;
margin-right: 10%;
position: absolute;
right: 0;
top: 0;
z-index: 10;
}
.about__button {
border: 1px solid var(--text-color);
background-color: var(--bg-color);
border-radius: 50%;
color: var(--text-color);
cursor: pointer;
font-size: 0.6rem;
height: 10%;
position: absolute;
right: 10px;
top: 10px;
width: 10%;
padding-left: 6px;
text-align: center;
text-decoration: none;
text-transform: none;
}
.about__button--close-modal {
border: 1px solid var(--bg-color);
background-color: var(--text-color);
border-radius: 5px;
color: var(--bg-color);
cursor: pointer;
font-size: 0.7rem;
height: 20px;
position: absolute;
right: 5px;
top: 5px;
width: 21px;
padding-left: -0.7rem;
text-align: center;
text-decoration: none;
text-transform: none;
}
.closed {
display: none;
}
.geo-details {
margin-bottom: 1.5rem;
}
.geo-details__date {
margin-bottom: 0.6rem;
}
.weather__temp {
display: inline;
position: relative;
padding-right: 1.3rem;
}
.weather__temp::after {
border: 2px solid var(--text-color);
border-radius: 50%;
content: '';
height: 0.5rem;
position: absolute;
right: 10px;
top: 2.3px;
width: 0.5rem;
}
.radio__list {
border: none;
display: inline;
margin: 0;
padding: 0;
}
.radio__item {
position: absolute;
left: -999px;
overflow: hidden;
}
.label__item {
color: inherit;
cursor: pointer;
background-color: inherit;
border: none;
font-size: inherit;
font-family: inherit;
margin: 0;
opacity: 0.4;
padding: 0;
}
.copyright {
background-color: var(--bg-color);
border-radius: 5px;
bottom: 10px;
position: fixed;
right: 10px;
text-decoration: none;
}
.copyright__text {
color: var(--text-color);
display: inline-block;
font-size: 0.7rem;
opacity: 0.8;
padding-bottom: 0.1rem;
padding-left: 0.3rem;
padding-right: 0.3rem;
}
.copyright__text a {
color: inherit;
}
.copyright__sign {
height: 25px;
vertical-align: middle;
width: 30px;
color: #fff;
/*color: var(--bg-color);
fill: var(--text-color);*/
}
.vivid {
opacity: inherit;
}
.vague {
opacity: 0.4;
}
.font--bigger {
font-size: 2rem;
}
/* css reset */
div, p, span {
margin: 0;
padding: 0;
}
html {
box-sizing: border-box;
}
*, *:before, *:after {
box-sizing: inherit;
}
body {
height: 100vh;
font-family: "Exo 2", "Lato", "PT Sans", -apple-system, BlinkMacSystemFont, "Roboto", "Ubuntu", "Droid Sans", "Helvetica Neue", "Arial", sans-serif;
font-size: 1rem;
background-repeat: no-repeat;
background-position: center center;
background-size: cover;
background-color: #fff;
color: #fff;
}
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
} else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
// here the function from https://stackoverflow.com/a/5882352
function readCookie(name) {
return (name = new RegExp('(?:^|;\\s*)' + ('' + name).replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&') + '=([^;]*)').exec(document.cookie)) && name[1];
}
function eraseCookie(name) {
createCookie(name,"",-1);
}
function capitalize(sentence) {
return sentence[0].toUpperCase() + sentence.substr(1);
}
function errorHandler(error) {
console.log(`Got error - ${error.message},\n${err.stack}`);
}
function getWeatherColor(temp_c) {
let colors = {};
if (30 <= temp_c) colors = { main: '#A50021', support: '#fff'};
else if (25 <= temp_c && temp_c < 30) colors = { main: '#D82632', support: '#fff'};
else if (20 <= temp_c && temp_c < 25) colors = { main: '#F76D5E', support: '#242442'}; //support: #fff - bad accessibility
else if (15 <= temp_c && temp_c < 20) colors = { main: '#FFAD72', support: '#00365c'};
else if (10 <= temp_c && temp_c < 15) colors = { main: '#FFE099', support: '#001F66'};
else if (5 <= temp_c && temp_c < 10) colors = { main: '#FFFFBF', support: '#000040'};
else if (0 <= temp_c && temp_c < 5) colors = { main: '#E0FFFF', support: '#1F0000'};
else if (-5 <= temp_c && temp_c < 0) colors = { main: '#AAF7FF', support: '#1F0000'};
else if (-10 <= temp_c && temp_c < -5) colors = { main: '#72D8FF', support: '#1F0000'};
else if (-15 <= temp_c && temp_c < -10) colors = { main: '#3FA0FF', support: '#1F0000'};
else if (-20 <= temp_c && temp_c < -15) colors = { main: '#264CFF', support: '#fcc'};
return colors;
}
function getWeatherImage(conditions, seasonYear) {
// weather determitants:
// - conditions as returned by weather API
// - current local season of the year;
// - latitude (north or south hemisphere);
// - current local time; ???
let backgroundImage;
let credit = {};
let credits = {
flurries: { author: 'Frida',
URL: 'https://flic.kr/p/k7zUGc',
license: 'CC BY-NC 2.0',
licenseURL: 'https://creativecommons.org/licenses/by-nc/2.0' },
snow: { author: 'FHKE',
URL: 'https://flic.kr/p/7AVLQR',
license: 'CC BY-SA 2.0',
licenseURL: 'https://creativecommons.org/licenses/by-sa/2.0' },
storm: { author: 'Kuster & Wildhaber Photography',
URL: 'https://flic.kr/p/cESNRS',
license: 'CC BY-ND 2.0',
licenseURL: 'https://creativecommons.org/licenses/by-nd/2.0' },
fog: { author: 'Martin Fisch',
URL: 'https://flic.kr/p/dkqP1t',
license: 'CC BY-SA 2.0',
licenseURL: 'https://creativecommons.org/licenses/by-sa/2.0' },
hazy: { author: 'pnwbot',
URL: 'https://flic.kr/p/pusoD1',
license: 'CC BY-NC-SA 2.0',
licenseURL: 'https://creativecommons.org/licenses/by-nc-sa/2.0' },
rain: { author: 'Gabriele Diwald',
URL: 'https://flic.kr/p/dfkuTL',
license: 'CC BY 2.0',
licenseURL: 'https://creativecommons.org/licenses/by/2.0'},
sunny: { winter: { author: 'bfatphoto',
URL: 'https://flic.kr/p/RHwJiG',
license: 'CC BY-NC-ND 2.0',
licenseURL: 'https://creativecommons.org/licenses/by-nc-nd/2.0' },
spring: { author: 'Stanley Zimny',
URL: 'https://flic.kr/p/oavqBk',
license: 'CC BY-NC 2.0',
licenseURL: 'https://creativecommons.org/licenses/by-nc/2.0' },
summer: { author: 'Chris',
URL: 'https://flic.kr/p/fgLTUU',
license: 'CC BY-SA 2.0',
licenseURL: 'https://creativecommons.org/licenses/by-sa/2.0'},
fall: { author: 'Jorge Franganillo',
URL: 'https://flic.kr/p/i28UqP',
license: 'CC BY 2.0',
licenseURL: 'https://creativecommons.org/licenses/by/2.0' }},
cloudy: { summer: { author: 'Kay Gaensler',
URL: 'https://flic.kr/p/cScQxy',
license: 'CC BY-NC-SA 2.0',
licenseURL: 'https://creativecommons.org/licenses/by-nc-sa/2.0' },
winter: { author: 'Peter Toporowski',
URL: 'https://flic.kr/p/RDW4Z1',
license: 'CC BY 2.0',
licenseURL: 'https://creativecommons.org/licenses/by/2.0' }},
partlysunny: { winter: { author: 'Gérald Laik',
URL: 'https://flic.kr/p/RzuZS7',
license: 'CC BY-NC-ND 2.0',
licenseURL: 'https://creativecommons.org/licenses/by-nc-nd/2.0' },
spring: { author: 'Graham Haley',
URL: 'https://flic.kr/p/UtjTDm',
license: 'CC BY-SA 2.0',
licenseURL: 'https://creativecommons.org/licenses/by-sa/2.0' },
summer: { author: 'Nicolas Raymond',
URL: 'http://freestock.ca/skies_clouds_g61-coastal_clouds__hdr_p1879.html',
license: 'CC BY 2.0',
licenseURL: 'https://creativecommons.org/licenses/by/2.0'}},
mostlysunny: { winter: { author: 'Adam Tas',
URL: 'https://flic.kr/p/R33zcf',
license: 'CC BY 2.0',
licenseURL: 'https://creativecommons.org/licenses/by/2.0' },
spring: { author: 'Jim Choate',
URL: 'https://flic.kr/p/SbmJj2',
license: 'CC BY-NC-ND 2.0',
licenseURL: 'https://creativecommons.org/licenses/by-nc-nd/2.0' },
summer: { author: 'Nicolas Raymond',
URL: 'http://freestock.ca/canada_g92-beaver_brook_scenery__hdr_p804.html',
license: 'CC BY 2.0',
licenseURL: 'https://creativecommons.org/licenses/by/2.0' },
fall: { author: 'Belinda Church',
URL: 'https://flic.kr/p/qb4cbs',
license: 'CC BY 2.0',
licenseURL: 'https://creativecommons.org/licenses/by/2.0' }}
};
switch (conditions) {
case 'chanceflurries':
case 'chancesleet':
case 'flurries':
case 'sleet':
backgroundImage = `img/flurries.jpg`;
credit = credits.flurries;
break;
case 'chancesnow':
case 'snow':
backgroundImage = `img/snow.jpg`;
credit = credits.snow;
break;
case 'chancetstorms':
case 'tstorms':
backgroundImage = `img/storm.jpg`;
credit = credits.storm;
break;
case 'fog':
backgroundImage = `img/fog.jpg`;
credit = credits.fog;
break;
case 'hazy':
backgroundImage = `img/hazy.jpg`;
credit = credits.hazy;
break;
case 'chancerain':
case 'rain':
backgroundImage = `img/rain.jpg`;
credit = credits.rain;
break;
case 'clear':
case 'sunny':
backgroundImage = `img/sunny_${seasonYear}.jpg`;
credit = credits.sunny[seasonYear];
break;
case 'cloudy':
if (seasonYear === 'spring' || seasonYear === 'fall') seasonYear = 'summer';
backgroundImage = `img/cloudy_${seasonYear}.jpg`;
credit = credits.cloudy[seasonYear];
break;
case 'mostlycloudy':
case 'partlysunny':
if (seasonYear === 'fall') seasonYear = 'spring';
backgroundImage = `img/partlysunny_${seasonYear}.jpg`;
credit = credits.partlysunny[seasonYear];
break;
case 'mostlysunny':
case 'partlycloudy':
backgroundImage = `img/mostlysunny_${seasonYear}.jpg`;
credit = credits.mostlysunny[seasonYear];
break;
}
return { image: backgroundImage, credit };
}
function displayData(data) {
const bodyElm = document.querySelector('body');
const mainElm = document.querySelector('.main');
const dateElm = document.querySelector('.geo-details__date');
const timeElm = document.querySelector('.geo-details__time');
const placeElm = document.querySelector('.geo-details__place');
const skyElm = document.querySelector('.weather__sky');
const tempElm = document.querySelector('.weather__temp');
const tempFScaleLabelElm = document.querySelector('.label__item--fahrenheit');
const tempCScaleLabelElm = document.querySelector('.label__item--celsius');
const tempFScaleInputElm = document.querySelector('.radio__item--fahrenheit');
const tempCScaleInputElm = document.querySelector('.radio__item--celsius');
const copyrightTextElm = document.querySelector('.copyright__text');
//const copyrightSignElm = document.querySelector('.copyright__sign');
const userScale = readCookie('scale');
dateElm.innerText = data.currDate;
timeElm.innerText = data.currTime;
placeElm.innerText = data.place;
tempElm.innerText = userScale === 'celsius' ? data.temp_c : data.temp_f;
// set visual appearance of the page
let seasonYear;
if (data.currMonth < 3 || data.currMonth === 12) {
seasonYear = data.hemisphere === 'north' ? 'winter' : 'summer';
} else if (3 <= data.currMonth && data.currMonth < 6) {
seasonYear = data.hemisphere === 'north' ? 'spring' : 'fall';
} else if (6 <= data.currMonth && data.currMonth < 9) {
seasonYear = data.hemisphere === 'north' ? 'summer' : 'winter';
} else if (9 <= data.currMonth && data.currMonth < 12) {
seasonYear = data.hemisphere === 'north' ? 'fall' : 'spring';
}
const bgImage = getWeatherImage(data.conditions, seasonYear);
// all inner visual appearance decisions are based on celsius scale;
const weatherColors = getWeatherColor(data.temp_c);
document.documentElement.style.setProperty('--bg-color', weatherColors.main);
document.documentElement.style.setProperty('--text-color', weatherColors.support);
// unable to set svg properties through css variables, so work directly
//copyrightSignElm.style.color = weatherColors.main;
//copyrightSignElm.style.fill = weatherColors.support;
const imgPrefix = 'https://al1s.github.io/WeatherNow/';
bodyElm.style.backgroundImage = `url('${imgPrefix + bgImage.image}')`;
copyrightTextElm.innerHTML = `<p>Photo by <a href='${bgImage.credit.URL}'>${bgImage.credit.author}</a>, <a href='${bgImage.credit.licenseURL}'>${bgImage.credit.license}</a>.</p>`;
// set scale and switch handlers
if (userScale === 'celsius') toggleButtonsState(tempCScaleLabelElm, tempFScaleLabelElm);
else toggleButtonsState(tempFScaleLabelElm, tempCScaleLabelElm);
function cScaleClickHandler(e) {
if ((e.type === 'keypress' && (e.keyCode === 13 || e.keyCode === 32)) ||
e.type === 'click') {
tempElm.innerText = data.temp_c;
if (readCookie('scale')) eraseCookie('scale');
createCookie('scale','celsius',300)
toggleButtonsState(tempCScaleLabelElm, tempFScaleLabelElm);
}
}
function fScaleClickHandler(e) {
if ((e.type === 'keypress' && (e.keyCode === 13 || e.keyCode === 32)) ||
e.type === 'click') {
tempElm.innerText = data.temp_f;
if (readCookie('scale')) eraseCookie('scale');
createCookie('scale','fahrenheit',300)
toggleButtonsState(tempFScaleLabelElm, tempCScaleLabelElm);
}
}
function toggleButtonsState(btn_pressed, btn_released) {
if (btn_pressed.innerText === 'F') {
var addHandler = cScaleClickHandler;
var removeHandler = fScaleClickHandler;
var inputCheckedElm = tempFScaleInputElm;
var inputUncheckedElm = tempCScaleInputElm;
} else if (btn_pressed.innerText === 'C') {
var addHandler = fScaleClickHandler;
var removeHandler = cScaleClickHandler;
var inputCheckedElm = tempCScaleInputElm;
var inputUncheckedElm = tempFScaleInputElm;
}
btn_pressed.classList.add('vivid');
inputCheckedElm.setAttribute('aria-checked', 'true');
btn_pressed.removeEventListener('click', removeHandler);
btn_pressed.removeEventListener('keypress', removeHandler);
btn_released.classList.remove('vivid');
inputUncheckedElm.setAttribute('aria-checked', 'false');
btn_released.addEventListener('click', addHandler);
btn_released.addEventListener('keypress', addHandler);
}
}
function getWeatherForPosition(pos) {
//const httpAddr = `https://api.wunderground.com/api/c29706cb930a70b9/conditions/q/${pos.coords.latitude},${pos.coords.longitude}.json`;//Kenmore,WA
const httpAddr = `https://api.wunderground.com/api/c29706cb930a70b9/conditions/q/${pos}.json`;
if (!fetch) alert('fetch() unavailable');
console.log(pos);
fetch(httpAddr)
.then(resp => {
if (resp.ok) {
return resp.json();
}
throw new Error();
})
.then(data => {
const obz = data.current_observation;
const loc = obz.display_location;
const place = loc.city + ', ' + (loc.country === 'US' ? loc.state : loc.state_name) + (loc.country === 'US' ? (', ' + loc.country) : '');
const time = obz.local_epoch;
let d = new Date(0);
d.setUTCSeconds(time);
const dayOptions = { weekday: 'long' };
const dateOptions = { month: 'long',
day: 'numeric' };
const timeOptions = { hour: 'numeric',
minute: 'numeric' };
const currDay = d.toLocaleDateString(undefined, dayOptions);
const currDate = d.toLocaleDateString(undefined, dateOptions);
const currTime = d.toLocaleTimeString(undefined, timeOptions);
const currMonth = d.getMonth() + 1;
const sky = obz.weather;
const temp = obz.temperature_string;
const temp_c = obz.temp_c;
const temp_f = obz.temp_f;
const tempFeels = obz.feelslike_string;
const tempFeelsC = obz.feelslike_c;
const tempFeelsF = obz.feelslike_f;
const conditions = obz.icon;
return {
place,
hemisphere: pos.split(',')[0] > 0 ? 'north' : 'south',
currDay,
currDate,
currTime,
currMonth,
sky,
temp,
temp_f,
temp_c,
tempFeels,
tempFeelsF,
tempFeelsC,
conditions
}
})
.then(data => displayData(data))
.catch (error => console.log(`Error while retrieving weather data - ${error.msg}`));
}
function geoLocFail(error) {
let msg = '';
switch(error) {
case 1: //error.PERMISSION_DENIED:
msg = "User denied the request for Geolocation.";
break;
case 2: //error.POSITION_UNAVAILABLE:
msg = "Location information is unavailable.";
break;
case 3: //error.TIMEOUT:
msg = "The request to get user location timed out.";
break;
case -3:
msg = error.message;
default:
msg = error.message;
break;
}
//alert('Geolocation error: ' + msg); // it's alert because we need to catch it on mobile platforms
getLocationByIP(); //fallback to get alternative user location;
}
function getLocation() {
if(navigator.geolocation) {
const location_timeout = setTimeout(function() {
let error = new Error();
error.code = -3;
error.message = 'Timer runout';
geoLocFail(error);
}, 0.2 * 10 * 1000);
//console.log('we are in main process');
navigator.geolocation.getCurrentPosition(function(position) {
clearTimeout(location_timeout);
console.log('successfully get geoposition');
getWeatherForPosition(position.coords.latitude + ',' + position.coords.longitude);
}, function(error) {
clearTimeout(location_timeout);
console.log('failed to get geoposition');
geoLocFail(error);
}, { timeout: 0.2 * 10 * 1000, maximumAge:60 * 10 * 1000, enableHighAccuracy: false });
} else {
let error = new Error();
error.message = 'An unknown error occurred';
error.code = -999;
geoLocFail(err);
}
}
function getLocationByIP() {
fetch('https://freegeoip.net/json/')
.then(resp => {
if (resp.ok) return resp.json();
throw new Error();
})
.then(data => {
getWeatherForPosition(data.latitude + ',' + data.longitude);
})
.catch(error => geoLocFail(error))
}
getLocation();
const aboutBtn = document.querySelector('.about__button');
aboutBtn.addEventListener('click', function() {
const aboutMsg = document.querySelector('.about');
aboutMsg.classList.toggle('closed');
});
const aboutCloseBtn = document.querySelector('.about__button--close-modal');
aboutCloseBtn.addEventListener('click', function() {
const aboutMsg = document.querySelector('.about');
aboutMsg.classList.toggle('closed');
});
Also see: Tab Triggers