Pen Settings

HTML

CSS

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. You can use the CSS from another Pen by using it's URL and the proper URL extention.

+ 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

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.

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

              
                <body id="background-image">
  <div class="container">
    <div class="wrapper row">
      <div class="card p-5 col-10 offset-3 col-md-8 col-lg-6 in-wrapper">
        <h1 class="mb-1">Show the Local Weather</h1>
        <div id="errors"></div>
        <div class="row">
          <div class="col-lg-6" id="location-data"></div>
          <div class="col-lg-6">
            <div id="temp-data"></div>
          </div>
        </div>
        <button id="switch-unit" class="btn btn-primary d-none mt-1" onclick="switchUnit()"></button>
      </div>
    </div>
  </div>
</body>
              
            
!

CSS

              
                #background-image {
  //background-image: url('');
  background-repeat: no-repeat;
  background-size: cover;
}

.wrapper {
  position: relative;
  height: 100vh;
}

.in-wrapper {
  position: absolute;
  top: 50%;
  left: 25%;
  transform: translate(-50%, -50%);
}
              
            
!

JS

              
                //settings
var convertToFahrenheit = false;
var oTemp;
var DEBUG = true;

(function() {
  getLocation();
})();

function getLocation() {
  if (navigator.geolocation) {
    if (DEBUG) console.log("Browser has function location ✔");
    navigator.geolocation.getCurrentPosition(getWeatherData);
    if (typeof navigator.geolocation.getCurrentPosition(test) === "undefined") {
      console.log("TEST: " + navigator.geolocation.getCurrentPosition(test));
      console.warn(`Maybe not authorized to get location 😔
So let's show testdata at startup`);

      console.log("TestData at getLocation(): " + getTestData());
      showData(getTestData());
    }
    function test(e) {
      return e.coords.latitude;
    }
  } else {
    var x = document.getElementById("errors");
    x.innerHTML = "Geolocation is not supported by this browser. 😔";
  }
}

function getWeatherData(position) {
  if (DEBUG) console.log("Got location data ✔");
  let latitude = Number(Math.round(position.coords.latitude + "e4") + "e-4");
  let longitude = Number(Math.round(position.coords.longitude + "e4") + "e-4");
  if (DEBUG)
    console.log(`https://www.google.be/maps/@${latitude},${longitude},14z`);
  getData(`https://fcc-weather-api.glitch.me/api/current?lat=${latitude}&lon=${longitude}`);
  if (typeof data == "undefined") {
    console.warn("There was an error with the response 😔😒🤷‍♂️");   
  }
  showData(data);
}

function getData(sLink) {
  if (DEBUG) console.log(sLink);
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4) {
      if (this.status == 200) {
        data = this.responseText;
      } else {
        console.log("Status: " + this.status);
        data = null;
      }
    }

    if (DEBUG) {
      switch (this.readyState) {
        case 0:
          console.log("Not initalized");
          break;
        case 1:
          console.log("Conection established");
          break;
        case 2:
          console.log("Request received");
          break;
        case 3:
          console.log("Processing request");
          break;
        case 4:
          console.log("Request finished and response ready");
          break;
        default:
          console.log("Weird readyState? " + this.readyState);
      }
    }
  };
  xhttp.open("GET", sLink, true);
  xhttp.send();
}

function showData(data) {
  oData = JSON.parse(data);
  if (DEBUG) console.log(oData);
  oTemp = {
    temp: oData.main.temp,
    min: oData.main.temp_min,
    max: oData.main.temp_max,
    unit: "°C"
  };
  if (DEBUG) console.log(oTemp);

  if (convertToFahrenheit) {
    oTemp = convertTo("farenheit", oTemp);
  }
  var x = document.getElementById("location-data");
  x.innerHTML = `The current weather in ${oData.name}, ${oData.sys.country}:`;

  let aWeather = oData.weather;
  if (aWeather.length > 0) {
    aWeather.forEach(function(e) {
      if (DEBUG) console.log(e);
      if (e.icon) {
        x.innerHTML += `<img src="${e.icon}" alt="${e.description}">`;
      }
      x.innerHTML += `<div>${e.main}: ${e.description}</div>`;
    });
  }
  showTemp(document.getElementById("temp-data"), oTemp);
  if (oData.weather[0].main) {
    showBackgroundImage(
      document.getElementById("background-image"),
      oData.weather[0].main
    );
  }
}
function showBtn(unit) {
  var btn = document.getElementById("switch-unit");
  unit = unit == "°C" ? "°F" : "°C";
  btn.innerHTML = `Switch to ${unit}`;
  // remove class d-none
  btn.className = btn.className.replace(/\bd-none\b/g, "");
}
function showTemp(x, oTemp) {
  x.innerHTML = `
<ul>
<li>${Number(Math.round(oTemp.temp + "e2") + "e-2")} ${oTemp.unit}</li>
<li>min: ${Number(Math.round(oTemp.min + "e2") + "e-2")} ${oTemp.unit}</li>
<li>max: ${Number(Math.round(oTemp.max + "e2") + "e-2")} ${oTemp.unit}</li>
</ul>`;

  showBtn(oTemp.unit);
}
function switchUnit() {
  if (oTemp.unit == "°F") {
    convertTo("celsius", oTemp);
  } else {
    convertTo("farenheit", oTemp);
  }
  showTemp(document.getElementById("temp-data"), oTemp);
}
function convertTo(to, temp) {
  if (to == "farenheit") {
    temp.temp = toFerenheit(temp.temp);
    temp.min = toFerenheit(temp.min);
    temp.max = toFerenheit(temp.max);
    temp.unit = "°F";
  }
  if (to == "celsius") {
    temp.temp = toCelsius(temp.temp);
    temp.min = toCelsius(temp.min);
    temp.max = toCelsius(temp.max);
    temp.unit = "°C";
  }
  if (DEBUG) console.log(temp);
  return temp;

  function toFerenheit(temp) {
    return temp * 9 / 5 + 32;
  }

  function toCelsius(temp) {
    return (temp - 32) * 5 / 9;
  }
}
function showBackgroundImage(x, weather) {
  var weather = weather.toLowerCase();
  if (DEBUG) console.log(weather);
  switch (weather) {
    case "rain":
      addImage(x, "https://wallpaperplay.com/walls/full/3/1/b/50027.jpg");
      break;
    case "clouds":
      addImage(x, "https://wallpaperplay.com/walls/full/3/3/e/51356.jpg");
      break;
    case "snow":
      addImage(x, "https://wallpaperplay.com/walls/full/5/8/0/76401.jpg");
      break;
    case "clear":
      addImage(
        x,
        "https://c.pxhere.com/photos/63/ba/sky_background_nature_blue_clouds_blue_sky_climate_clear-639846.jpg!d"
      );
    default:
      if (DEBUG) console.log("Unspecified weather");
      //default image
      addImage(x, "https://wallpaperplay.com/walls/full/3/1/b/50027.jpg");
  }

  function addImage(x, url) {
    x.style.backgroundImage = `url('${url}')`;
  }
}

/***********************************
 * If project has to many request
 * Show the test data
 ***********************************/
function getTestData() {
  return '{"coord":{"lon":3.75,"lat":51.04},"weather":[{"id":520,"main":"Rain","description":"light intensity shower rain","icon":"https://cdn.glitch.com/6e8889e5-7a72-48f0-a061-863548450de5%2F09d.png?1499366021170"}],"base":"stations","main":{"temp":9.99,"pressure":991,"humidity":93,"temp_min":8.89,"temp_max":11.11},"visibility":4600,"wind":{"speed":11.3,"deg":260},"clouds":{"all":99},"dt":1574937376,"sys":{"type":1,"id":1553,"country":"Nerdland","sunrise":1574925695,"sunset":1574955868},"timezone":3600,"id":2793070,"name":"Ledeberg","cod":200}';
}

              
            
!
999px

Console