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

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

              
                <html>
  <head>
    <title>JTA Weather App</title>
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.1/css/all.css" integrity="sha384-50oBUHEmvpQ+1lW4y57PTFmhCaXp0ML5d60M1M7uH2+nqUivzIebhndOJK28anvf" crossorigin="anonymous"/>
  </head>
  
  <body>
    <div id="main">
      <h1>The JTA Weather App</h1>
      <div id="loc-bar">
        <h3 id="location">Location: Loading...</h3>
        <form action="javascript:changeLocation();">
          <input id="search" type=text size=15>
          <input type="submit" id="button" value="Search">
        </form>
      </div>
      <div id="hist-bar">
      </div>
      <div id="summary">
        <div id="icon"></div><div id="status"></div>
        <div id="current-temp"></div> 
        <div id="f-or-c" onclick="switchFC()"></div>
      </div>
      <div id="details">
        <div id="temps"></div>
        <div id="humidity"></div>
      </div>
      <div id="extras">
        <div id="wind-container">
          <span style="font-size: 1.5rem">Wind Information:</span>
          <div id="wind-group">
            <div id="wind"><div id="direction"></div></div>
            <div id="wind-info"></div>
          </div>
        </div>
        <div id="daylight"></div>
      </div>
      <div id="map">
        <iframe id="weathermap" src="" width="100%" frameborder="0" allowfullscreen></iframe>
      </div>
      <footer>©2022 - kinome79 Weather App - a freeCodeCamp project</footer>
    </div>
  </body>
</html>
              
            
!

CSS

              
                *{
  box-sizing: border-box;
}

body {
  background: black center/cover no-repeat url("https://kinome79.github.io/images/weather_background.jpg");
  color: white;
}

#main {
  display: flex; 
  flex-direction: column;
  align-items: center;
  margin: auto;
  padding: 20px;
  width: 800px;
  background: rgba(0,0,75,.8);
  border-radius: 20px;
  box-shadow: 5px 5px 30px 10px black;
  font-size: 1.3rem;
  color: #DDDDFF;
}
.waiting {
  cursor: wait;
}

h1 {
  padding: 0;
  margin: 15px;
}

h3 {
  padding: 0;
  margin: auto;
}

#loc-bar{
  display: flex;
  padding: 2px;
  width: 100%;
  height: 35px;
  text-align: center;
  background-color: blue;
  color: white;
  border-radius: 10px 10px 0 0;
  box-shadow: 5px 5px 10px black;
  .latlon {
    font-size: 1.0rem;
  }
}

#search, #button {
}

#hist-bar {
  display: flex;
  width: 100%;
  height: 20px;
  /*background-color: lightgrey;*/
  border-radius: 0 0 10px 10px;
  color: black;
  .hist-btn {
    position: relative;
    width: 20%;
    height: 100%;
    padding-left: 5px;
    padding-right: 5px; 
    text-align: center;
    overflow: hidden;
    font-size: .8rem;
    cursor: pointer;
    border: outset 2px black;
    border-radius: 0 0 10px 10px;  
    background-color: lightgrey;
    box-shadow: 3px 3px 10px black;
    &:hover {
      background-color: lightblue;
    }
    &:hover .hist-del{
      display: block;
    }
    .hist-del {
      position: absolute;
      padding: 0;
      margin: 0;
      right: 5px;
      top: 1px;
      width: 12px;
      height: 12px; 
      color: black;
      font-size: .7rem;
      display: none;
      &:hover {
        color: red;
      }
    }
  }
}

#summary {
  margin: 15px;
  margin-top: 30px;
  display: flex; 
}

#icon {
  padding-top: 10px;
  width: 75px;
  height: 75px;
}

#status {
  padding-top: 10px;
  margin-left: 20px;
  width: 200px;
  .stat {
    font-size: 3rem;
  }
  .desc {
    font-size: 1.3rem;
  }
}

#current-temp {
  width: 200px;
  margin-left: 25px;
  position: relative;
}
.current-temp {
  font-size: 3.5rem;
  padding-top: 10px;
  .feels {
    font-size: .7rem;
  }
}

#f-or-c {
  position: relative;
  text-align: center;
  padding-top: 1px;
  width: 35px;
  height: 32px;
  font-size: 1.5rem;
  background-color: grey;
  color: black;
  right: 115px;
  top: 20px;
  cursor: pointer;
  border-radius: 5px;
  border-top: 2px solid white;
  border-left: 2px solid white;
  border-bottom: 2px solid black;
  border-right: 2px solid black;
}
#f-or-c:hover {
  background-color: #DDDDDD;
}
#f-or-c:active {
  background-color: green;
}

#details {
  margin: 15px;
  display: flex;
}

#temps {
  width: 225px;
  margin-left: 45px;
}

#humidity {
  width: 200px; 
  margin-left: 35px;
}

#extras {
  display: flex;
  margin: 15px;
}

#wind-container {
  font-size: 1.7rem;
  width: 225px;
  margin-left: 30px;
}
#wind-group {
  display: flex;
  padding: 10px;
  font-size: 1.1rem;
}
#wind {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  background-color: lightgrey;
  box-shadow: 0px 0px 10px black;
  margin-right: 10px;
  margin-top: 5px;
}

#direction{
  position: relative;
  left: 28px;
  top: 7px;
  width: 3px;
  height: 45px;
  transition: transform 5s;
  background-color: red;
}
#direction:before {
  content: '';
  border: 6px solid transparent;
  border-top: 6px solid red;
  position: absolute;
  top: 42px;
  left: -5px;
}

#wind-info {
  margin-left: 5px;
}

#daylight {
  margin-left: 70px;
  padding-top: 5px;
}

.title {
  font-size: 1.3rem;
}

#map {
  margin: 30px 0px;
  width: 450px;
  height: 350px;
}

#weathermap {
  border-radius: 20px;
  border:0;
  width:100%;
  height:100%;
  box-shadow: 5px 5px 10px black;
}

.value {
  color: #FFCCCC;
}

footer {
  font-size: 1.2rem;
}
              
            
!

JS

              
                //Global Variables: 
//is_f - tracks farenhiet vs celcius, myTemps - stores globally temp data for function use, myBtns - id counter for tabs
let is_f = window.localStorage.getItem('is_f') == "true" ? true : false;
let myTemps;
let myBtns = 0;

//Runs on document loaded - starts the browser geolocation search and loads tabs-------------------------------------
document.addEventListener("DOMContentLoaded", function() {
  //Set waiting mouse cursor, load location tabs
  document.getElementById("main").classList.add('waiting');
  loadTabs();
  //Check for geolocation compatibility, call getWeatherInfo with geodata or default lat,lon
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(getWeatherInfo, geoError);
  } else {
    alert("Cannot Get Location: GeoLocation not currently availabe in this browser! Using default location!");
    getWeatherInfo({coords: {latitude: 33.6054149, longitude: -112.125051}});
  }
});

//Runs if geolocation errors - gets weather with default lat/lon-----------------------------------------------
function geoError() {
  alert("Cannot Get Location: GeoLocation failed to provide information! Using default location!");
  getWeatherInfo({coords: {latitude: 33.6054149, longitude: -112.125051}});
}

//function - use FCC weather API and gets weather for provided position, updates html elements with the info----------
function getWeatherInfo(position) {  
  const BASEURL = "https://weather-proxy.freecodecamp.rocks/api/current";

  //default lat,lon if none provided
  let lat = 33.6054149;
  let lon = -112.125051;
  
  //get lat,lon from provided position data
  if (position.coords.latitude) {
     lat = position.coords.latitude;
     lon = position.coords.longitude;
  }
  
  //create query URL for the API get request
  let query = "?lon=" + lon + "&lat=" + lat;
  let fullUrl = BASEURL + query;

  //Send get request to FCC weather API
  const req = new XMLHttpRequest();
  req.open("GET", fullUrl, true);
  req.send();
  req.onload = () => {
    const weather = JSON.parse(req.responseText);
    // default weather data - used while editing page design to prevent excessive requests during refreshes
   // const weather = {"coord":{"lon":-83.1053,"lat":40.0876},"weather":[{"id":804,"main":"Clouds","description":"overcast clouds","icon":"https://cdn.freecodecamp.org/weather-icons/04n.png"}],"base":"stations","main":{"temp":22,"feels_like":19.11,"temp_min":17.6,"temp_max":20.31,"pressure":1008,"humidity":87},"visibility":10000,"wind":{"speed":0.89,"deg":153,"gust":0.89},"clouds":{"all":92},"dt":1653022722,"sys":{"type":2,"id":2016648,"country":"US","sunrise":1653041568,"sunset":1653093924},"timezone":-14400,"id":5152333,"name":"Dublin","cod":200};
  
  //Pull weather variables from the returned weather data object
  lat = weather.coord.lat;
  lon = weather.coord.lon;
  let {main, description, icon} = weather.weather[0];
  myTemps = weather.main;
  let {speed, deg, gust} = weather.wind;
  let name = weather.name;
  let sunrise = new Date(weather.sys.sunrise*1000);
  let sunset = new Date(weather.sys.sunset*1000);
  
  //Fill in HTML elements with provided weather data
  document.getElementById('location').innerHTML = 'Location: ' + name + 
    ' - <span class="latlon"> (Lat: ' +lat+ ', Lon: ' +lon + ')</span>';
  document.getElementById('icon').innerHTML = '<img src="' + icon + '" alt="Weather Icon" width="75" height="75"/>';
  document.getElementById('status').innerHTML = '<span class="stat">'+main + '</span><br> <span class="desc">' + description + '</span>';
  //function to fill in Tempurature HTML elements with appropriate f or c selector
  drawTemps();
  //Fill in remaining HTML elements with provided weather data, rotate the wind indicator element
  document.getElementById('direction').style.transform = "rotate(" + deg + "deg)";
  document.getElementById('wind-info').innerHTML = 'Vel: <span class="value">'+Math.round(speed*2.23694)+' mph</span><br>Gust:<span class="value"> '+ ((gust)? Math.round(gust*2.23694): "--")+' mph</span><br>From: <span class="value">'+ deg +'°</span>'
  document.getElementById('daylight').innerHTML = '<span class="title">Morning/Evening Times:</span> <br><br>Sunrise: <span class="value">'+makeTime(sunrise)+' <br></span>Sunset: <span class="value">' + makeTime(sunset)+" </span>";
   }
  //Provide src value for the weather map iframe based on lat,lon
  document.getElementById('weathermap').src = 'https://www.rainviewer.com/map.html?loc='+lat+','+lon+',10&oFa=0&oC=0&oU=0&oCS=0&oF=0&oAP=1&c=3&o=83&lm=1&layer=radar&sm=1&sn=1';
  //Remove the waiting mouse icon now that update is complete
  document.getElementById("main").classList.remove('waiting');
}

//Function returns an html color for a provided temperature based on its value (red=hot, blue=cold)
function tempColor (t) {
    if (t >= 29) {
      return'#DD0000';
    } else if (t < 29 && t >= 24 ) {
      return '#DDAA00';
    } else if (t < 24 && t >= 12 ) {
      return '#00DD00';
    } else if (t < 12 && t >= 0 ) {
      return '#00DDAA';
    } else if (t < 0) {
      return '#0000DD';
    }
    return '#FFFFFF'
}

//Function returns provided temp with appropriate f/c conversion based on global is_f variable
function convTemps(t) {
  if (is_f) {
    return (Math.round((t*9/5 + 32) * 10)/10);
  } else {
    return (Math.round(t*10)/10);
  }
}

//Function to update temperature related html elements with global temp data for when f/c is changed
function drawTemps() {
  //pull variables from global myTemps variable, convert and get temperature color
  let {temp, feels_like, temp_min, temp_max, humidity, pressure} = myTemps;
  let theColor = tempColor(temp);
  temp = Math.round(convTemps(temp));
  let convTemp = convTemps(temp);
  
  //Fill in temperature related html elements with the data
  document.getElementById('current-temp').innerHTML = '<span class="current-temp" style="color: '+theColor+'">'+temp+'°</span> <span class="feels"><br>Feels Like <span class="value">' + convTemps(feels_like) + '°</span></span>';
  document.getElementById('f-or-c').innerHTML = is_f?"F":"C";
  document.getElementById('temps').innerHTML = 'Today\'s High: <span class="value">' + convTemps(temp_max) + '°</span><br>Today\'s Low: <span class="value">' + convTemps(temp_min) + "°</span>";
  document.getElementById('humidity').innerHTML = 'Humidity: <span class="value">' + humidity + ' % </span><br>Pressure: <span class="value">' + pressure + ' hpa</span>';
}

//Function executes on F/C button press - changes global is_f and update temps
function switchFC() {
  is_f = !is_f;
  window.localStorage.setItem('is_f', is_f);
  drawTemps();
}

//Function accepts date object, returns a readable 12hr time string
function makeTime(t) {
  let hr = parseInt(t.getHours());
  let mins = t.getMinutes();
  let ampm = hr > 11?"PM":"AM";
  if (hr == 0) {
    hr = 12;
  } else if (hr > 12) {
    hr = hr - 12;
  }
  
  return hr + ":" + (mins < 10? "0" + mins : mins) + " " + ampm;
}

//Runs on form Search button press, use openstreetmap api to get lat,lon from search query
function changeLocation () {
  //Get value from text input, setup URL for get request
  const BASEURL = "https://nominatim.openstreetmap.org/search";
  let query = document.getElementById("search").value;
  document.getElementById("search").value = "";
  let queryurl = "?q="+query+"&format=json&limit=1"
  let fullUrl = BASEURL + queryurl;
  
  if (query.length > 0) {
    //Set mouse icon and header to waiting status
    document.getElementById("main").classList.add('waiting');
    document.getElementById("location").innerHTML = "Location: Loading...";
    //Sent GET request to openstreetmaps to get lat,lon from text input
    const req = new XMLHttpRequest();
    req.open("GET", fullUrl, true);
    req.send();
    req.onload = () => {
      const geodata = JSON.parse(req.responseText);
      
      //If found - perform weather lookup with new lat,lon and add a tab to the search bar
      if (geodata[0]) {
        let {lat,lon} = geodata[0];
        getWeatherInfo({coords: {latitude: lat, longitude: lon}});
        updateTabs(query, lat, lon);
      } else {   
        //Remove wait cursor and show error in header if geo search failed
        document.getElementById("main").classList.remove('waiting');
        document.getElementById("location").innerHTML = 'Error! "' + query + '" not found!' ;
      }
    }
  }
}

//Function executes when a quick location tab is pressed... performs weather lookup for stored lat,lon
function fastLocate(lat,lon) {
  //set waiting icon and header message, and perform weather lookup
  document.getElementById("main").classList.add('waiting');
  document.getElementById("location").innerHTML = "Location: Loading..."
  getWeatherInfo({coords: {latitude: lat, longitude: lon}});
}

//Function to add a tab to the tab bar, creates a tab with provided data if fewer than 5 already exist
function updateTabs(query, lat, lon) {
  if (document.querySelectorAll(".hist-btn").length < 5) {
    //update global tab index, add <div> element to tab bar
    myBtns++;
    document.getElementById("hist-bar").innerHTML = document.getElementById("hist-bar").innerHTML + 
        '<div id="btn'+myBtns+'" class="hist-btn" onclick="fastLocate('+lat+','+lon+')">'+query+'<div class="hist-del" onclick="deleteTab('+myBtns+')">X</div></div>';
    //Run function to save tabs to localStorage
    saveTabs();
  }
}

//Ran on delete tab button press, removes the selected dom element, updates tabbar in storage
function deleteTab(tab) {
  document.getElementById("btn" + tab).remove();
  event.stopPropagation();
  saveTabs();
}

//Ran on page load - Pulls the tab list from localStorage, updates tab bar if found... updates tab index 
function loadTabs() {
  const tabStr = window.localStorage.getItem('tabs');
  if (tabStr) {
    document.getElementById("hist-bar").innerHTML = tabStr;
    myBtns = parseInt(window.localStorage.getItem("tabIndex"));
  }
}

//Ran when tabbar is changed, saves tabbar contents and tab index to localStorage
function saveTabs() {
  const tabStr = document.getElementById("hist-bar").innerHTML;
  window.localStorage.setItem('tabs', tabStr);
  window.localStorage.setItem('tabIndex', myBtns);
}
              
            
!
999px

Console