I'm using some JS to calculate the time since last post (ie. "Posted 2 hours ago"):
function ago(date) {
function render(n, unit) {
return n + " " + unit + ((n == 1) ? "" : "s") + " ago";
}
var seconds = Math.floor((new Date() - date) / 1000);
var interval = Math.floor(seconds / (60 * 60 * 24 * 30 * 365));
if (Math.floor(seconds / (60 * 60 * 24 * 30 * 365)) >= 1) {
return render(interval, "year");
}
interval = Math.floor(seconds / (60 * 60 * 24 * 30));
if (interval >= 1) {
return render(interval, "month");
}
interval = Math.floor(seconds / (60 * 60 * 24));
if (interval >= 1) {
return render(interval, "day");
}
interval = Math.floor(seconds / (60 * 60));
if (interval >= 1) {
return render(interval, "hour");
}
interval = Math.floor(seconds / 60);
if (interval >= 1) {
return render(interval, "minute");
}
interval = Math.floor(seconds);
return render(interval, "second");
}
And then include it on the index page, next to each post:
var date =
Date.parse(document.getElementById("postedon").getAttribute("datetime"));
document.getElementById("postedago").innerHTML = ago(date);
Here is the HTML:
<time id="{{ post.postedon }}" datetime="{{ post.date | date_to_xmlschema }}">
<span id="{{ post.postedago }}"></span>
</time>
Note that I'm setting the element's ID and attributes in each post's frontmatter using Liquid & YAML (with Jekyll):
---
date: 2018-1-4 02:00:00 +0100
postedago: postedago-post1
postedon: postedon-post2
---
The issue is I have to set the JS code for each post manually like this:
var date =
Date.parse(document.getElementById("postedon").getAttribute("datetime"));
document.getElementById("postedago").innerHTML = ago(date);
var date =
Date.parse(document.getElementById("postedon2").getAttribute("datetime"));
document.getElementById("postedago2").innerHTML = ago(date);
var date =
Date.parse(document.getElementById("postedon3").getAttribute("datetime"));
document.getElementById("postedago3").innerHTML = ago(date);
Otherwise it won't display the time for all posts, just one.
I tried setting the element id in JS to the front matter parameter but it won't work (essentially having Jekyll replace liquid tags inside the JS file):
var date =
Date.parse(document.getElementById("{{ post.postedon }}").getAttribute("datetime"));
document.getElementById("{{ post.postedago }}").innerHTML = ago(date);
I tried adding the front-matter dashes at the top of the js file but it still doesn't work (as referenced on SO here: Reach Jekyll Variables With JavaScript and Pass it Throught DOM Manipulation)
---
---
//rest of your JavaScript
Maybe there's another way of doing this that I haven't thought of?
Thanks for taking your time to read this, I really appreciate any help!
PS: Reference timeago script implementation on each post's page (not on the index page containing all posts): https://hejnoah.com/posts/timeago.html