|
Displaying estimated delivery dates is a handy little feature in e-commerce that
gives useful information to customers and reassures them about the ordering
process.
Estimating delivery dates can be quite involved, but it’s easy to chuck a very
simple estimated delivery range on any page with these vanilla JavaScript
functions, no libraries required:
function showEstimatedDelivery() {
const estDelEls = document.querySelectorAll(".estimated-delivery");
if (!estDelEls || !estDelEls.length) {
return;
}
const [minDate, maxDate] = estimatedDeliveryRange();
const [minFormat, maxFormat] = [formatDate(minDate), formatDate(maxDate)];
let estimatedDelivery
if (minFormat === maxFormat) {
estimatedDelivery = minFormat;
} else {
estimatedDelivery = `${minFormat} — ${maxFormat}`;
}
document.querySelectorAll(".estimated-delivery").forEach((el) => {
el.innerHTML = estimatedDelivery;
})
}
const SATURDAY = 6
const SUNDAY = 0
function estimatedDeliveryRange(from = new Date(), minWorkDays = 8, maxWorkDays = 10) {
const time = new Date(from.getTime())
time.setHours(12, 0, 0, 0)
let minDate
let maxDate
while (minWorkDays > 0 || maxWorkDays > 0) {
time.setHours(time.getHours() + 24)
if (time.getDay() !== SATURDAY && time.getDay() !== SUNDAY) {
minWorkDays--
maxWorkDays--
if (minWorkDays <= 0 && !minDate) {
minDate = new Date(time.getTime())
}
if (maxWorkDays <= 0 && !maxDate) {
maxDate = new Date(time.getTime())
}
}
}
return [minDate, maxDate]
}
function formatDate(date = new Date()) {
return new Intl.DateTimeFormat("en-GB", {
weekday: 'short',
day: 'numeric',
month: 'short',
}).format(date);
}
We use this on our static e-commerce site Moment Wall
Art, for example on this Japanese wall art
print
product page.
View post:
Simple estimated delivery dates in vanilla JS
|
|
|
|