Hi guys, I received great help from @anthonysalamin with creating a difference in today’s date and published date. However result shows up for just one collection item, instead of the entire collection items. I understand i need to create a For Loop javascript for it to work. My javascript is next to zero and need help with this.
@webdev is right, if you wanted to target several CMS items you could have used classes instead of my initial id idea
Here is the depedency free snipet I had in mind which involves a bit more javascript gymnastic than other libraries available out there but therefore also highly customizable since you can define the formatting yourself.
Pure vanilla JavaScript
/*
* Time from now
* dependency free 🍉
*/
(function timeFromNow() {
// 🧠 helpers
const oneDay = 24 * 60 * 60 * 1000; // in milliseconds
// 🧠 get current date
const now = new Date(),
Fullyear = now.getFullYear(),
month = now.getMonth() + 1,
day = now.getDate(),
currentDate = new Date(Fullyear, month, day);
const wrappers = document.getElementsByClassName("featured-content-block");
for (let i = 0; i < wrappers.length; i++) {
let wrapper = wrappers[i];
// 🧠 get published date (YY/MM/DD)
let published = wrapper.querySelector(".published"),
stringDate = published.innerHTML,
arrayDate = stringDate.split("/"),
publishedDate = new Date(arrayDate[0], arrayDate[1], arrayDate[2]);
// 🧠 get date difference in days
let diffDays = Math.round(Math.abs((publishedDate - currentDate) / oneDay));
// 🧠 handle formatting
let year, plural, elapsedTime;
if (diffDays == 0) {
elapsedTime = `Today 🔥`;
} else if (diffDays == 1) {
elapsedTime = `Yesterday`;
} else if (diffDays < 365) {
elapsedTime = `${diffDays} days ago`;
} else {
year = Math.round(diffDays / 365);
if (year == 1) {
plural = "year";
} else {
plural = "years";
}
elapsedTime = `${year} ${plural} ago`;
}
// 🧠 inject value back into HTML layout
let elapsed = wrapper.querySelector(".elapsed");
elapsed.innerHTML = elapsedTime;
}
})();
Ho great ! Haven’t heard about moment.js ! Sounds intersting, will have a look !
Probably much less needed code than what I just shared
The native vanilla javascript way to get a date is kind of an overkill I must say !
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<script>
"use strict";
$(document).ready(function () {
var publishedDate = ".pub-date";
var displayDate = ".display-date";
$(publishedDate).each(function (i, e) {
/* @webdev - Jeff S.
* grab the text published date (hidden) value
* check it then convert it to a moment,
* get difference from today
* then put it in the .display-date element.
*/
var p = $(e).text();
var a = $(e).next(displayDate);
if (moment(p).isValid()) {
var m = moment(p);
var s = moment(m).fromNow();
a.text("Listed " + s);
}
});
});
</script>
Note that in this case, the element that gets the new value is the first sibling as referenced by .next().