123

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.

            
              <div class="container backgroundDiv">

  <!-- row for creating vertical margin -->
  <div class="row" style="margin:50px auto">
    <br>
  </div>

  <div class="row text-center">
    <span id="temperatureDisplay">.. </span><span id="tempUnit" class="clickable"> F</span>
  </div>

  <div class="row text-center">
    <p id="rainStatus">rain status here</p>
    <small>weather from forecast.io</small>
  </div>

  <div class="row text-center">
    <p class="small">by <a href="https://sg.linkedin.com/in/nickangtc">nick ang</a></p>
  </div>

</div>
            
          
!
            
              body {
  background-color: skyblue;
}

.backgroundDiv {
	background: skyblue;
	background-position: center center;
	background-size: cover;
}

a {
    color: black;
}
a:hover {
  color: black;
}

.clickable {
  color: blue;
}
            
          
!
            
              $(document).ready(function() {

  // All global variables
  var latitude = 0;
  var longitude = 0;
  var tempF = 0; // Fahrenheit, forecast.io default unit
  var tempC = 0; // Celsius
  var clouds = 0;
  var rain = 0;
  var rainIcon = ""; // machine-readable rain status
  var clickCount = 0; // for toggling between F and C

  /// Promise 1: resolve when location obtained from browser navigator
  // promises used here to make async processes run in sync fashion (navigator -> GET request)
  var getLocation = function() {
    return new Promise(function(resolve, reject) {
      function error() { // if geolocation cannot be obtained
        $("#locationMessage").text("Can't get your location");
        console.log("couldn't get location.");
      }
      // Function to execute when geolocation is successfully obtained
      function success(position) {
        // Code to run when latitude and longitude obtained successfully.
        latitude = Math.round(position.coords.latitude * 100) / 100;
        longitude = Math.round(position.coords.longitude * 100) / 100;
        console.log("lat: " + latitude, "long: " + longitude);
        resolve(latitude, longitude);
      }
      navigator.geolocation.getCurrentPosition(success, error);
    })
  }

  /// Promise 2: resolve when weather JSON object accessed from forecast.io
  // Using JSONP to work around cross-domain XMLHttpRequest
  var fetchWeather = function(latitude, longitude) {
    return new Promise(function(resolve, reject) {
      var apiKey = "17dcb6e003313f2ac0aac35bd2575d05"; // forecast.io API
      function getJSONP() {
        $.ajax({
          url: "https://api.forecast.io/forecast/" + apiKey + '/' + latitude + ',' + longitude,
          dataType: "jsonp",
          success: function(data) {
            tempF = Math.floor(data.currently.temperature * 10) / 10; // forecast.io API returns fahrenheit by default
            tempC = Math.round((tempF - 32) * 5 / 9 * 10) / 10; // convert to Celsius
            rain = data.currently.summary;
            clouds = data.currently.cloudCover;
            rainIcon = data.currently.icon;
            console.log("Temp in Fahrenheit: " + tempF);
            console.log("Temp in Celsius: " + tempC);
            console.log(rain, "rainIcon: " + rainIcon);
            console.log("Cloud cover: " + clouds);
            $("#temperatureDisplay").text(tempF); // display tempF via html
            $("#rainStatus").text(rain); // display rain status via html
          }
        });
      }
      resolve (getJSONP());
    })
  }

  // Determine weather image to display in background
  var bgWeather = function() {
    console.log("bg image loaded.");
    if (rainIcon == "partly-cloudy-day") {
      var rainImg = "https://pixabay.com/static/uploads/photo/2015/05/08/11/02/open-road-757949_960_720.jpg";
      $('.backgroundDiv').css('background-image', 'url(' + '"' + rainImg + '"' + ')');
    }
  }

  /// Promise queuing
  // #1: get location
  // #2: use location and get weather json object
  // #3: use weather data (data.currently.icon) to set background image
  getLocation().then(function() {
    return fetchWeather(latitude,longitude);
  }).then(function() {
    bgWeather(rainIcon)
  }, errorHandling);
  
  function errorHandling () {
    console.log(arguments);
  }

  /// JS for HTML manipulation

  // Toggle button for Fahrenheit/Celsius change
  $("#tempUnit").on("click", function() {
    if (clickCount % 2 === 0) {
      $("#temperatureDisplay").text(tempC);
      $("#tempUnit").text(" C");
      clickCount++;
    } else {
      $("#temperatureDisplay").text(tempF);
      $("#tempUnit").text(" F");
      clickCount++;
    }
  })

  /// End JS for HTML manipulation

})
            
          
!
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.

Console