HTML preprocessors can make writing HTML more powerful or convenient. For instance, Markdown is designed to be easier to write and read for text documents and you could write a loop in Pug.
In CodePen, whatever you write in the HTML editor is what goes within the <body>
tags in a basic HTML5 template. So you don't have access to higher-up elements like the <html>
tag. If you want to add classes there that can affect the whole document, this is the place to do it.
In CodePen, whatever you write in the HTML editor is what goes within the <body>
tags in a basic HTML5 template. If you need things in the <head>
of the document, put that code here.
The resource you are linking to is using the 'http' protocol, which may not work when the browser is using https.
CSS preprocessors help make authoring CSS easier. All of them offer things like variables and mixins to provide convenient abstractions.
It's a common practice to apply CSS to a page that styles elements such that they are consistent across all browsers. We offer two of the most popular choices: normalize.css and a reset. Or, choose Neither and nothing will be applied.
To get the best cross-browser support, it is a common practice to apply vendor prefixes to CSS properties and values that require them to work. For instance -webkit-
or -moz-
.
We offer two popular choices: Autoprefixer (which processes your CSS server-side) and -prefix-free (which applies prefixes via a script, client-side).
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.
You can apply CSS to your Pen from any stylesheet on the web. Just put a URL to it here and we'll apply it, in the order you have them, before the CSS in the Pen itself.
You can also link to another Pen here (use the .css
URL Extension) and we'll pull the CSS from that Pen and include it. If it's using a matching preprocessor, use the appropriate URL Extension and we'll combine the code before preprocessing, so you can use the linked Pen as a true dependency.
JavaScript preprocessors can help make authoring JavaScript easier and more convenient.
Babel includes JSX processing.
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.
You can apply a script from anywhere on the web to your Pen. Just put a URL to it here and we'll add it, in the order you have them, before the JavaScript in the Pen itself.
If the script you link to has the file extension of a preprocessor, we'll attempt to process it before applying.
You can also link to another Pen here, and we'll pull the JavaScript from that Pen and include it. If it's using a matching preprocessor, we'll combine the code before preprocessing, so you can use the linked Pen as a true dependency.
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.
Using packages here is powered by esm.sh, which makes packages from npm not only available on a CDN, but prepares them for native JavaScript ESM usage.
All packages are different, so refer to their docs for how they work.
If you're using React / ReactDOM, make sure to turn on Babel for the JSX processing.
If active, Pens will autosave every 30 seconds after being saved once.
If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.
If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.
Visit your global Editor Settings.
<main id="container" class="daymode">
<time id="date" class="clocktext"></time>
<time id="time" class="clocktext"></time>
<button type="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 + " " + 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;
}
Also see: Tab Triggers