Skip to content

Instantly share code, notes, and snippets.

@rosszurowski
Last active August 29, 2015 14:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rosszurowski/317ed2a58d54b792ed41 to your computer and use it in GitHub Desktop.
Save rosszurowski/317ed2a58d54b792ed41 to your computer and use it in GitHub Desktop.
Custom Elements
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Timestamp Demo</title>
</head>
<body>
<x-timestamp>05/05/2015</x-timestamp>
<script src="timestamp.js"></script>
</body>
</html>
"use strict";
class Timestamp extends HTMLElement {
attachedCallback() {
this.dataset.date = Date.parse(this.textContent);
requestAnimationFrame(this.update.bind(this));
}
update() {
let now = Date.now();
let diff = now - this.dataset.date;
this.textContent = diff.getUTCSeconds() + ' seconds';
requestAnimationFrame(this.update.bind(this));
}
detachedCallback() {
clearInterval(this.timer);
}
}
document.registerElement('x-timestamp', Timestamp);
/**
* Get a relative date string ("x minutes ago") from a timestamp
*/
function relativeTime(ms){
var SECOND_MS = 1000;
var MINUTE_MS = 60 * SECOND_MS;
var HOUR_MS = 60 * MINUTE_MS;
var DAY_MS = 24 * HOUR_MS;
var WEEK_MS = 7 * DAY_MS;
var MONTH_MS = 30 * DAY_MS;
var lookup = ["months", "weeks", "days", "hours", "minutes", "seconds"];
var values = [];
values.push(ms / MONTH_MS); ms %= MONTH_MS;
values.push(ms / WEEK_MS); ms %= WEEK_MS;
values.push(ms / DAY_MS); ms %= DAY_MS;
values.push(ms / HOUR_MS); ms %= HOUR_MS;
values.push(ms / MINUTE_MS); ms %= MINUTE_MS;
values.push(ms / SECOND_MS); ms %= SECOND_MS;
var pretty = "About ";
for(var i=0 ; i <values.length; i++){
var val = Math.round(values[i]);
if(val <= 0) continue;
pretty += val + " " + lookup[i] + " ago";
break;
}
return pretty;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment