Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

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.

+ add another resource

JavaScript

Babel includes JSX processing.

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

Packages

Add Packages

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.

Behavior

Auto Save

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.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                  <main class="main">
    <h1 class="header">Your local weather conditions.</h1>
    <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>
<!--
    <div class="modal">
      <form action="/" class="search">
        <input type="text" class="search__box" placeholder="Your location">
        <button class="btn  search__btn">Get weather!</button>
        <button class="btn">Use GPS</button>
      </form>
    </div>
-->
  </main>
<div class="color-range">
  
</div>

              
            
!

CSS

              
                root {
  --text-color: #5B87D0;
  --bg-color: #5B87D0;
}

.main {
  background-color: var(--bg-color);
  border-radius: 5px;
  color: var(--text-color);
  display: inline-block;
  margin-left: 10vw;
  margin-top: 15vh;
  opacity: 0.8;
  padding: 1rem;
  position: fixed;
  text-transform: uppercase;
  }

.header {
  margin: 0;
  padding: 0;
  line-height: 0;
  width: 0;
  visibility: hidden;
}

.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 {
  left: -999px;
  position: absolute;
  overflow: hidden;
}


.label__item {
  background-color: inherit;
  border: none;
  color: inherit;
  cursor: pointer;
  font-family: inherit;
  font-size: inherit;
  margin: 0;
  opacity: 0.4;
  padding: 0;
}
.vivid {
  opacity: inherit;
}

.font--bigger {
  font-size: 2rem;
}

.color-range {
  background-image: linear-gradient(to right, 
    #264CFF,
    #3FA0FF,
    #72D8FF,
    #AAF7FF,
    #E0FFFF,
    #FFFFBF,
    #FFE099,
    #FFAD72,
    #F76D5E,
    #D82632,
    #A50021
  );
  bottom: 0;
  left: 0;
  right: 0;
  position: fixed;
  height: 1vh;
  width: 100%;
}

/* css reset */
div, p, span {
  margin: 0;
  padding: 0;
}

html {
  box-sizing: border-box;
}
*, *:before, *:after {
  box-sizing: inherit;
}

body {
  background-color: #5B87D0;
  color: #5B87D0;
  font-family: "Exo 2", "Lato", "PT Sans", -apple-system, BlinkMacSystemFont, "Roboto", "Ubuntu", "Droid Sans", "Helvetica Neue", "Arial", sans-serif;
  font-size: 1rem;
}


              
            
!

JS

              
                  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=/";
  }

// 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 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', contrast: '#fff'};
    else if (20 <= temp_c && temp_c < 25) colors = { main: '#F76D5E', contrast: '#242442'}; //support: #fff - bad accessibility
    else if (15 <= temp_c && temp_c < 20) colors = { main: '#FFAD72', contrast: '#00365c'};
    else if (10 <= temp_c && temp_c < 15) colors = { main: '#FFE099', contrast: '#001F66'};
    else if (5 <= temp_c && temp_c < 10) colors = { main: '#FFFFBF', contrast: '#000040'};
    else if (0 <= temp_c && temp_c < 5) colors = { main: '#E0FFFF', contrast: '#1F0000'};
    else if (-5 <= temp_c && temp_c < 0) colors = { main: '#AAF7FF', contrast: '#1F0000'};
    else if (-10 <= temp_c && temp_c < -5) colors = { main: '#72D8FF', contrast: '#1F0000'};
    else if (-15 <= temp_c && temp_c < -10) colors = { main: '#3FA0FF', contrast: '#1F0000'};
    else if (-20 <= temp_c && temp_c < -15) colors = { main: '#264CFF', contrast: '#fcc'};
    return colors;
  }

  function displayData(data) {
    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 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 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
    const weatherColors = getWeatherColor(data.temp_c); // all inner visual appearance decisions are based on celsius scale;
    mainElm.style.color = weatherColors.contrast;
    mainElm.style.backgroundColor = weatherColors.main;
    window.getComputedStyle(
      document.querySelector('.weather__temp'), ':after').getPropertyValue('color')
    
    // 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}.json`;
    if (!fetch) console.error('fetch() unavailable');

  fetch(httpAddr)
    .then(resp => {
      if (resp.ok) return resp.json();
      throw new Error();
    })
    .then(data => {
      const currentCondition = data.current_observation;
      const loc = currentCondition.display_location;
      const place = loc.city + ', ' + (loc.country === 'US' ? loc.state : loc.state_name) +  (loc.country === 'US' ? (', ' + loc.country) : '');
      const time = currentCondition.local_epoch;
      let d = new Date(0);
      d.setUTCSeconds(time);
      const dateOptions = { month: 'long',
                           day: 'numeric' };
      const timeOptions = { hour: 'numeric',
                           minute: 'numeric' };
      const currDate = d.toLocaleDateString(undefined, dateOptions);
      const currTime = d.toLocaleTimeString(undefined, timeOptions);
      const temp_c = currentCondition.temp_c;
      const temp_f = currentCondition.temp_f;
      const conditions = currentCondition.icon;
      return { place, currDate, currTime, temp_f, temp_c, conditions }
    })
    .then(data => displayData(data))
    .catch (error => console.error(`Error - ${error.msg}, ${error.stack}`));
  }

  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;
    }
    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);
      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(error);
    }
  }

  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();
              
            
!
999px

Console