css Audio - Active file-generic CSS - Active Generic - Active HTML - Active JS - Active SVG - Active Text - Active file-generic Video - Active header Love html icon-new-collection icon-person icon-team numbered-list123 pop-out spinner split-screen star tv

Pen Settings

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

You're using npm packages, so we've auto-selected Babel for you here, which we require to process imports and make it all work. If you need to use a different JavaScript preprocessor, remove the packages in the npm tab.

Add External Scripts/Pens

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.

+ add another resource

Use npm Packages

We can make npm packages available for you to use in your JavaScript. We use webpack to prepare them and make them available to import. We'll also process your JavaScript with Babel.

⚠️ This feature can only be used by logged in users.

Code Indentation

     

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

HTML Settings

Here you can Sed posuere consectetur est at lobortis. Donec ullamcorper nulla non metus auctor fringilla. Maecenas sed diam eget risus varius blandit sit amet non magna. Donec id elit non mi porta gravida at eget metus. Praesent commodo cursus magna, vel scelerisque nisl consectetur et.

            
              <body id="weather-app" class="clear">
    <div class="flex-container flex-container-style fixed-height">
        <div class="flex-item">
            <div class="flex-middle">
                <div class="weatherbox wrapper">
                    <div class="icon">
                        <i id="weather-icon" class="wi wi-day-sunny"></i>
                    </div>
                    <div class="temp">
                        <span id="temp-value">0</span>
                        <sup>&deg;</sup>
                        <span id="temp-unit" class="temp-unit-of-measure pointer converter-link">C</span>
                    </div>
                    <!-- /.temp -->
                    <div class="wind">
                        <i id="wind-icon" class="wi wi-wind towards-23-deg"></i>
                        <span id="wind-speed">0</span>
                        <span id="speed-unit" class="pointer converter-link">km/h</span>
                    </div>
                    <div class="city ">
                        <span id="city-name"></span>
                        <sup id="city-country"></sup>
                    </div>
                </div>
                <!-- /.weatherbox wrapper -->

            </div>
        </div>
    </div>

    <div id="coordinates " style="visibility: hidden; z-index: 99999; display: none " data-latitude="0
                            " data-longitude="0 "></div>
   <!--  <script type="module" src="/weather.js"></script> -->
</body>
            
          
!
            
              * {
  padding: 0;
  margin: 0;
}

/* height */
.flex-container {
  display: -ms-flexbox;
  display: -webkit-box;
  display: flex;
  -ms-flex-direction: column;
  -webkit-box-orient: vertical;
  -webkit-box-direction: normal;
          flex-direction: column;
  -ms-flex-wrap: nowrap;
  flex-wrap: nowrap;
  -ms-flex-pack: center;
  -webkit-box-pack: center;
          justify-content: center;
  -ms-flex-line-pack: center;
  align-content: center;
  -ms-flex-align: center;
  -webkit-box-align: center;
          align-items: center;
}

.flex-item:nth-child(1) {
  -ms-flex-order: 0;
  -webkit-box-ordinal-group: 1;
          order: 0;
  -ms-flex: 0 1 auto;
  -webkit-box-flex: 0;
          flex: 0 1 auto;
  -webkit-align-self: center;
  -ms-flex-item-align: center;
  align-self: center;
}

.flex-middle {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-align: center;
      -ms-flex-align: center;
          align-items: center;
}

body {
  font-size: 18px;
  background-color: #b0cce6;
  background-image: url("https://picsum.photos/1200/800/?random");
  background-size: cover;
}

@media (min-width: 320px) {
  body {
    font-size: calc(2.23214vw + 10.85714px);
  }
}

@media (min-width: 768px) {
  body {
    font-size: calc(5.46875vw - 14px);
  }
}

@media (min-width: 1024px) {
  body {
    font-size: calc(1.92308vw + 22.30769px);
  }
}

@media (min-width: 1440px) {
  body {
    font-size: 50px;
  }
}

body.drizzle {
  background-image: url("https://picsum.photos/1200/800/?image=178");
}

body.clouds {
  background-image: url("https://picsum.photos/1200/800/?image=651");
  background-position: top center;
}

body.rain {
  background-image: url("https://picsum.photos/1200/800/?image=542");
}

body.snow {
  background-image: url("https://picsum.photos/1200/800/?image=730");
}

body.clear {
  background-image: url("https://picsum.photos/1200/800/?image=845");
}

body.thunderstorm {
  background-image: url("https://picsum.photos/1200/800/?image=149");
}

.flex-container-style {
  background-image: radial-gradient(transparent 30%, rgba(0, 0, 0, 0.4) 70%, rgba(0, 0, 0, 0.75) 95%), -webkit-gradient(linear, left bottom, left top, from(rgba(0, 0, 0, 0.3)), color-stop(15%, transparent), color-stop(85%, transparent), to(rgba(0, 0, 0, 0.3))), -webkit-gradient(linear, left top, right top, from(rgba(0, 0, 0, 0.3)), color-stop(15%, transparent), color-stop(85%, transparent), to(rgba(0, 0, 0, 0.3)));
  background-image: radial-gradient(transparent 30%, rgba(0, 0, 0, 0.4) 70%, rgba(0, 0, 0, 0.75) 95%), linear-gradient(to top, rgba(0, 0, 0, 0.3) 0%, transparent 15%, transparent 85%, rgba(0, 0, 0, 0.3)), linear-gradient(to right, rgba(0, 0, 0, 0.3) 0%, transparent 15%, transparent 85%, rgba(0, 0, 0, 0.3));
}

.fixed-height {
  height: 100vh;
}

.weatherbox {
  background-color: rgba(0, 0, 0, 0.85);
  color: white;
  padding: 10vh 20vw;
  border: 4px solid rgba(255, 255, 255, 0.15);
  border-radius: 16px;
  text-align: center;
}

.temp {
  font-size: 2em;
}

.temp-unit-of-measure {
  font-size: 0.75em;
}

.temp sup {
  font-size: 0.35em;
}

.icon i {
  font-size: 3.5em;
}

.wind i {
  font-size: 1.2em;
}

.city {
  font-size: 1.5em;
  color: dimgray;
  padding-top: 0.15em;
}

.city sup {
  font-size: 0.5em;
}

.pointer:hover {
  cursor: pointer;
}

.converter-link {
  color: cornflowerblue;
}

.converter-link:hover {
  color: orangered;
}

            
          
!
            
              // Set script as module
// https://blog.codepen.io/2017/12/26/adding-typemodule-scripts-pens/
import { getNodes } from 'https://codepen.io/chriscoyier/pen/LeNmrX.js';

// Arrays

const arrWeatherCondition = ['drizzle', 'clouds',  'rain', 'snow',  'clear', 'thunderstorm'];
const arrWindClasses = [ 'towards-0-deg', 'towards-23-deg', 'towards-45-deg', 'towards-68-deg', 'towards-90-deg', 'towards-113-deg', 'towards-135-deg', 'towards-158-deg', 'towards-180-deg', 'towards-203-deg', 'towards-225-deg', 'towards-248-deg', 'towards-270-deg', 'towards-293-deg', 'towards-313-deg', 'towards-336-deg' ];

// Functions

function convertTemperature() {
    let unitOfMeasure = document.getElementById('temp-unit').innerHTML.toUpperCase();
    let temperatureValue = document.getElementById('temp-value').innerHTML;
    if (unitOfMeasure == 'C') {
        document.getElementById('temp-unit').innerHTML = 'F';
        document.getElementById('temp-value').innerHTML = Math.round(temperatureValue * 9 / 5 + 32);
    } else if (unitOfMeasure == 'F') {
        document.getElementById('temp-unit').innerHTML = 'C';
        document.getElementById('temp-value').innerHTML = Math.round((temperatureValue - 32) * 5 / 9);
    }
}


function convertSpeed() {
    let unitOfMeasure = document.getElementById('speed-unit').innerHTML.toLowerCase();
    let speedValue = document.getElementById('wind-speed').innerHTML;
    if (unitOfMeasure == 'km/h') {
        document.getElementById('speed-unit').innerHTML = 'mph';
        document.getElementById('wind-speed').innerHTML = roundToOne(speedValue*0.62137);
    } else if (unitOfMeasure == 'mph')  {
        document.getElementById('speed-unit').innerHTML = 'km/h';
        document.getElementById('wind-speed').innerHTML = roundToOne(speedValue/0.62137);
    }
}
/**
 * 
 * @link https://stackoverflow.com/a/18358056
 * @param {any} num 
 * @returns 
 */
function roundToOne(num) {    
    return +(Math.round(num + 'e+1')  + 'e-1');
}

/* Random number generator */
const randomRange = (randomRangeMax, randomRangeMin = 1) => Number(Math.floor(Math.random() * (randomRangeMax - randomRangeMin + 1)) + randomRangeMin);

/* Nudge wind direction to closer reflect the major directions set in arrWindClasses*/
const windRange = (windRangeDegree, windRangeAdjust = 11.25) => Math.round(windRangeDegree + windRangeAdjust);

/* Return the appropriate weather icons wind icon class according to wind degree */
const windIconClass = (windIconClassDegree, windIconClassArray) => windIconClassArray[parseInt(windIconClassDegree / 22.5)]; 

/* Get element my tag name */
const elTag = (htmlTag, num = 0) => document.getElementsByTagName(htmlTag)[num];

/* Get element by ID name */
const elID = (id) => document.getElementById(id);

/* Remove current weather condition class and replace with another class */
const swopClass = (element, oldClass = '', newClass) => {
    if (Array.isArray(oldClass)) {
        oldClass.forEach((condition, index) => {
            element.classList.remove(oldClass);
        });} else if (oldClass.length > 0){
        element.classList.remove(oldClass);
    }
    element.classList.add(newClass);
};

function changeMainWeatherIcon(condition)  {
    switch (condition){
    case 'drizzle': 
        swopClass(document.getElementById('weather-icon'),'wi-day-sunny', 'wi-day-sleet'); 
        break;
    case 'clouds': 
        swopClass(document.getElementById('weather-icon'),'wi-day-sunny', 'wi-day-cloudy'); 
        break;
    case 'rain': 
        swopClass(document.getElementById('weather-icon'),'wi-day-sunny', 'wi-day-wind'); 
        break;
    case 'snow': 
        swopClass(document.getElementById('weather-icon'),'wi-day-sunny', 'wi-day-snow');
        break;
    case 'clear': 
        swopClass(document.getElementById('weather-icon'),'wi-day-sunny', 'wi-day-sunny'); 
        break;
    case 'thunderstorm': 
        swopClass(document.getElementById('weather-icon'),'wi-day-sunny', 'wi-day-thunderstorm');
        break;
    }
}

/* Write content to element */
const writeHtmlContent = (element, content) => element.innerHTML = content;

/* function unixTimeStamp(t) // For use if you want to show sunrise/sunset time
{
    const dt = new Date(t*1000);
    const hr = dt.getHours();
    const m = '0' + dt.getMinutes();
    const s = '0' + dt.getSeconds();
    return hr+ ':' + m.substr(-2) + ':' + s.substr(-2);  
} */

/**
 * Get Weather
 * 
 * GEOLOCATION
 * Get geolocation Lat and Lon
 * Set string 
 * 
 * WEATHER API
 * Fetch weather api
 * 
 */

// GEOLOCATION
const coordinates = document.getElementById('coordinates');

// Inspired by: 
// https://www.sitepoint.com/community/t/using-global-variable-outside-scope-of-function/34260

if (navigator.geolocation) { // Check to see if this browser supports geolocation.
    navigator.geolocation.getCurrentPosition((position) => {
        const myLat = position.coords.latitude;
        const myLon = position.coords.longitude;
        // coordinates.dataset.latitude = myLat;
        // coordinates.dataset.longitude = myLon;
        const weatherAPI = `https://fcc-weather-api.glitch.me/api/current?lat=${myLat}&lon=${myLon}`;
        console.log(weatherAPI);

        const weatherBox = document.querySelector('.weatherbox');
        zlFetch(weatherAPI).then(function (data) {
            // console.log(data);
            return showWeather(weatherBox, data);
        }).catch(function (error) {
            writeError(weatherBox, error);
        });
        

    });
}


/**
 * TODO: 
 * Display weather condition textually ?
 * Sunrise/set times ? 
 * */

        
function showWeather(targetDiv, weatherData) {
    const weatherTemp = weatherData.main.temp;
    const weatherCity = weatherData.name;
    const weatherCountry = weatherData.sys.country;
    const weatherDescription = weatherData.weather[0].main.toLowerCase();
    const weatherWindSpeed = weatherData.wind.speed;
    const weatherWindDegree = weatherData.wind.deg;
    // const weatherSunRise = unixTimeStamp(weatherData.sys.sunrise); // UNCOMMENT unixTimestamp function for this
    // const weatherSunSet = unixTimeStamp(weatherData.sys.sunset); // UNCOMMENT unixTimestamp function for this
    swopClass(elTag('body'), 'clear', weatherDescription);
    writeHtmlContent(elID('temp-value'), weatherTemp);
    writeHtmlContent(elID('wind-speed'), weatherWindSpeed);
    writeHtmlContent(elID('city-name'), weatherCity);
    writeHtmlContent(elID('city-country'), weatherCountry);
    
    swopClass(document.getElementById('wind-icon'), 'towards-23-deg', windIconClass(windRange(weatherWindDegree), arrWindClasses));
    changeMainWeatherIcon(weatherDescription);

}

document.getElementById('temp-unit').addEventListener ('click', convertTemperature);
document.getElementById('speed-unit').addEventListener ('click', convertSpeed);

/**
 * https://github.com/zellwk/zl-fetch
 * See: https://css-tricks.com/using-fetch/
 * 
 * For Codepen use: https://codepen.io/zellwk/pen/BRBeKN
 * 
 * @name zlFetch
 * @author Zell Liew
 * @description zlFetch is a library that abstracts away the handleResponse function so you can skip ahead to and handle both your data and errors without worrying about the response.
 * @param {*} url 
 * @param {*} options 
 */

/* global fetch */
export default function zlFetch (url, options = undefined) {
    return fetch(url, optionsHandler(options))
        .then(handleResponse);
}
  
export function optionsHandler (options) {
    let def = {
        method: 'GET',
        headers: {'Content-Type': 'application/json'}
    };
  
    if (!options) return def;
  
    let r = Object.assign({}, def, options);
    if (objectHasKey(options, 'token')) {
        delete r.token;
        r.headers.Authorization = 'Bearer ' + options.token;
    }
  
    delete r.body;
    if (options.body) {
        if (!objectIsEmpty(options.body)) {
            r.body = JSON.stringify(options.body);
        }
    }
  
    return r;
}
  
export const handlers = {
    JSONResponseHandler (response) {
        return response.json()
            .then(json => {
                if (response.ok) {
                    return json;
                } else {
                    return Promise.reject(Object.assign({}, json, {
                        statusCode: response.status, // statusCode is deprecated.
                        status: response.status
                    }));
                }
            });
    },
    textResponseHandler (response) {
        if (response.ok) {
            return response.text();
        } else {
            return Promise.reject(Object.assign({}, {
                statusCode: response.status,
                status: response.status,
                err: response.statusText
            }));
        }
    }
};
  
export function handleResponse (response) {
    let contentType = response.headers.get('content-type');
    if (contentType.includes('application/json')) {
        return handlers.JSONResponseHandler(response);
    } else if (contentType.includes('text/html')) {
        return handlers.textResponseHandler(response);
    } else {
        throw new Error(`Sorry, content-type ${contentType} not supported`);
    }
}
  
function objectIsEmpty (obj) {
    return (Object.getOwnPropertyNames(obj).length === 0);
}
  
function objectHasKey (o, prop) {
    return o.hasOwnProperty(prop);
}
// Writes Errors
function writeError(errorDiv, error) {
    var errorMessage = document.createElement('div');
    errorMessage.classList.add('is-error');
    errorMessage.innerHTML = '<div> status: ' + error.status + '</div>\n     <div> statusText: ' + error.statusText + ' </div>\n     <div> message: ' + error.message + ' </div>';
    errorDiv.append(errorMessage);
}
            
          
!
999px
🕑 One or more of the npm packages you are using needs to be built. You're the first person to ever need it! We're building it right now and your preview will start updating again when it's ready.
Loading ..................

Console