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.

            
              <main id="container" class="daymode">
	<time id="date" class="clocktext"></time>
	<time id="time" class="clocktext"></time>
	<button id="gpsbutton">Get Location and Weather</button>
	<div id="weather" class="clocktext infotext"></div>
	<img id="icon" src="https://openweathermap.org/img/w/01n.png" alt="weather icon"/>
	<div id="gps" class="clocktext infotext"></div>
</main>
  <!-- A simple clock that fits on an old iPhone 4s so you can reuse your old device as a wall clock. This version also includes geolocation and displays the current weather. -->
            
          
!
            
              html {font-size:16px;}
body {
    padding:0;
    margin:0;
    font-family:TrebuchetMS,Arial,sans-serif;
}
#container {
    margin:0 auto;
    padding:0;
    width:100vw;
    height:100vh;
    text-align:center;
    overflow:hidden;
}
.nightmode {
    background-color:#121212;
    background-image: linear-gradient(to bottom left, #121212 10%,#333955 100%);
    color:#fff;
    text-shadow:1px 1px 1px black;
}
.daymode {
    background-color: #87ceeb;
    background-image: linear-gradient(to bottom left, #87ceeb 0%,#fff 100%);
    color:#333;
    text-shadow:1px 1px 10px white;
}

@media (prefers-color-scheme: dark) {
  .daymode {
    background-color: #003;
    background-image: linear-gradient(to bottom left, #003 0%,#fff 100%);
    color:#ffc;
    text-shadow:1px 1px 10px black;
  }
}
.santamode {
    background-color: #0f3;
    background-image: linear-gradient(to bottom left, #0f3 0%,#fff 100%);
    color:#c00;
    text-shadow:1px 1px 10px white;
}
.clocktext {
    display:block;
    margin:0;
    padding:1px 0 0 0;
    width:100%;
    text-align:center;
    line-height:1.0;
    white-space:nowrap;
}
#date {
    font-size:1.3rem;
    padding-top:15px;
}
#time {
    font-size:5rem;
    margin:1px 0 0 0;
}
#time span {
    display:inline-block;
    padding:0;
    vertical-align: baseline;
    text-align:left;
    width: 2em;
    margin:0 0 0 0.5em;
    font-size:1.5rem;
    line-height:1.5;
    white-space:normal;
}
.infotext {
    margin:0;
    padding:0 5px 0 5px;
    font-size:1.3rem;
    line-height:1.4;
    width:auto;

}
#weather {display:block;width:auto;}
#icon {
    display:inline-block;
    opacity:0;
    vertical-align:top;
    width:50px;
    height:50px;
}
#gpsbutton {
    -webkit-appearance: none;
    -moz-appearance: none;
    display:block;
    margin:0 auto;
    padding:0 16px 0 16px;
    width:auto;
    height:40px;
    border:2px outset #fff;
    border-radius:12px;
    background:#dedeff;
    color:black;
    font-size:20px;
    cursor:pointer;
}
#gpsbutton:hover {
    background:#000033;
    border:2px inset #fff;
    color:#fff;
}
@media (min-width: 480px){
    #date {font-size:2rem;}
    #time {font-size:8rem;}
    #time span {
        font-size:2rem;
        line-height: 2;
    }
    .infotext {
        font-size:1.8rem;
    }
    #weather {display:inline-block;}
}
@media (min-width: 1000px){
    #icon {height:100px;width:100px;}
    #date {font-size:4rem;}
    #time {font-size:16rem;}
    #time span {
        font-size:4rem;
        line-height: 2;
    }
    .infotext {
        font-size:3.6rem;
    }
    #weather {display:inline-block;}
}

            
          
!
            
              //NOTE: ES5 chosen instead of ES6 for compatibility with older mobile devices
var now, dd, td;
var lat, lon, gd, gpsbutton;
var weatherurl, wd, icon;
var temperaturescale = "F"; //set to F or C (fahrenheit or celsius)
var usephp = false; // set to true to use a php document to hide your api key
var locationRequested = false;
var months = ["January","February","March","April","May","June","July","August","September","October","November","December"];
var days = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
var sunsettime = 0;
var sunrisetime = 0;
var iconurl = "https://openweathermap.org/img/w/";
var weatherminute;

document.addEventListener("DOMContentLoaded", init, false);
function init(){
  iconurl = "https://shearspiremedia.com/demos/icons4owm/"; //a set of custom icons I created
  dd = document.getElementById("date");
  td = document.getElementById("time");
  wd = document.getElementById("weather");
  gd = document.getElementById("gps");
  icon = document.getElementById("icon");
  weatherminute = randRange(0,14);
  gpsbutton = document.getElementById("gpsbutton");
  gpsbutton.addEventListener("click",getLocation,false);
  updateTime();
  setInterval(updateTime,1000);
}
function updateTime(){
  var clockdata = getClockStrings();
  dd.innerHTML = clockdata.datehtml;
  td.innerHTML = clockdata.timehtml;
  dd.dateTime = now.toISOString();
  td.dateTime = now.toISOString();
  var sec = now.getSeconds();
  var minutes = now.getMinutes();
  if (locationRequested && sec === 0){
    checkForSunset(); //checks for sunset once each minute
    if (minutes % 15 === weatherminute){
      getWeather(); //get weather every 15 minutes
      //weatherminute is a random number between
      //0 and 14 to ensure that users don't all hit
      //the API at the same minute
    }
    if (minutes % 5 === 0){
      getLocation(); //get location every 5 minutes while the app is running
    }
  }
}
function getClockStrings(){
  now = new Date();
  var year = now.getFullYear();
  var month = months[now.getMonth()];
  var date = now.getDate();
  var day = days[now.getDay()];
  var hour = now.getHours();
  var minutes = now.getMinutes();
  var seconds = now.getSeconds();
  var meridian = hour < 12 ? "AM" : "PM";
  var clockhour = hour > 12 ? hour - 12 : hour;
  if (hour === 0) {clockhour = 12;}
  var clockminutes = minutes < 10 ? "0" + minutes : minutes;
  var clockseconds = seconds < 10 ? "0" + seconds : seconds;
  var datehtml = day + ", " + month + " " + date + ", " + year;
  var timehtml = clockhour + ":" + clockminutes + "<span>:" + clockseconds + " " + meridian + "</span>";
  return {"datehtml":datehtml,"timehtml":timehtml};
}

function getLocation() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(showPosition,geoError);
  }else{
    gd.innerHTML = "location unknown";
    locationRequested = false;
  }
}
function geoError(){
  gd.innerHTML = "location unknown";
}
function showPosition(position) {
  gpsbutton.style.display = "none";
  lat = position.coords.latitude;
  lon = position.coords.longitude;
  gd.innerHTML = "GPS: " + lat.toFixed(2) + " | " + lon.toFixed(2);
  if (usephp){
    weatherurl = "clock.php?lat=" + lat + "&lon=" + lon;
    //weatherurl = "clock.php?lat=200&lon=200"; // for testing error response
  }else{    
    weatherurl = "https://api.openweathermap.org/data/2.5/weather?";
    weatherurl += "lat=" + lat + "&lon=" + lon + "&APPID=";
    weatherurl += YOUR_API_KEY_HERE;
    //for the APPID, please substitute your own API Key you can get for free from openweathermap.org
  }
  /*
        an alternative to exposing your API Key is to call a php script that
        calls the weatherurl and returns a json string as part of a document that
        can be parsed. Codepen doesn't allow php access so I established a throw-away
        account on openweathermap.org for this demonstration which has the apikey referenced here.

        for a working example that uses php to hide the api key see https://shearspiremedia.com/demos/clock/

        HERE IS A BASIC PHP SCRIPT THAT YOU COULD PLACE IN YOUR OWN clock.php file on your server
        <!DOCTYPE html>
        <html lang="en">
        <head><meta charset="UTF-8"><title>clock data</title></head>
        <body>
        <?php
        error_reporting(0);
        $latitude = "80";
        $longitude = "-85";
        if (isset($_GET["lat"]) && isset($_GET["lon"])) {
              $latitude = $_GET["lat"];
              $longitude = $_GET["lon"];
        }
        $endpoint = "http://api.openweathermap.org/data/2.5/weather?";
        $apikey = "YOUR_API_KEY_HERE";
        $weatherurl = $endpoint . "lat=" . $latitude . "&lon=" . $longitude . "&appid=" . $apikey;
        $jsonfile = file_get_contents($weatherurl);
        if ($jsonfile !== false){
            echo "$jsonfile";
        }else{
            echo '{"weather":[{"description":"Weather Unavailable","icon":"01n"}],"main":{"temp":255.372278}}';
        }
        ?>
        </body>
        </html>
        */
  if (!locationRequested){
    getWeather();
    locationRequested = true;
  }
}
function getWeather(){
  wd.innerHTML = "getting weather";
  // I opted to use the older XMLHttpRequest because fetch is not supported on old devices like the iPhone 4s
  // I developed this page so I could use my old iPhone 4s as a wall clock.
  var xhttp = new XMLHttpRequest();
  xhttp.responseType = usephp ? "document" : "text"; //the php file returns a document rather than plain text
  xhttp.onreadystatechange = function() {
    if (this.readyState === 4 && this.status === 200) {
      //when using php as a data source we need the textContent of the body of the returned document
      var data = usephp ? xhttp.response.body.textContent : xhttp.responseText;
      processWeather(JSON.parse(data));
    }
  };
  xhttp.open("GET", weatherurl, true);
  xhttp.send();
}
function convertTemperature(kelvin){
  //converts temps in kelvin to celsius or fahrenheit
  var celsius = (kelvin - 273.15);
  return temperaturescale === "F" ? celsius * 1.8 + 32 : celsius;
}
function processWeather(data){
  var weather = data["weather"][0];
  icon.src = iconurl + weather.icon + ".png";
  icon.style.opacity = 1;
  var localtemperature = convertTemperature(data["main"].temp).toFixed(0);
  var weatherstring = localtemperature + "°" + temperaturescale + "&nbsp;&nbsp;" + weather.description;
  wd.innerHTML = weatherstring;
  sunsettime = Number(data["sys"].sunset);
  sunrisetime = Number(data["sys"].sunrise);
  checkForSunset();
}

function checkForSunset(){
  var nowtime = now.getTime()/1000;
  //changes the presentation style if the time of day is after sunset
  //or before the next day's sunrise
  var isDark = nowtime > sunsettime || nowtime < sunrisetime;
  document.getElementById("container").className = isDark ? "nightmode" : "daymode";
  //uncomment the following if you want santa mode
  // if (now.getMonth() === 11 && now.getDate() <= 31){
  //   document.getElementById("container").className = "santamode";
  // }
}
//random number utility function
function randRange(min, max) {
  return Math.floor(Math.random()*(max-min+1))+min;
}
            
          
!
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