Skip to main content

Load LiveChat widget only at certain time

Introduction

This tutorial explains how to make your chat widget to be completely hidden out of your office hours. It presents how to make your chat widget to be available to customers only during some certain hours and days.

Live example

You can see how it works here

Checking current time and day

First we need to prepare a script that will check what is the day and hour for our timezone.

    <script>
var date = new Date();
var timezone = "Europe/Warsaw";
var optionsDay = { weekday: "long", timeZone: timezone };
var optionsHour = { hour: "numeric", timeZone: timezone };
var lcday = date.toLocaleDateString("en-EN", optionsDay);
var lchour = Number(date.toLocaleString("en-GB", optionsHour));
console.log(lcday + " " + lchour + "h");
</script>

The only part of the above code that you need to adjust on your side is the timezone. Please change the ‘Europe/Warsaw’ to any timezone needed. Remember to use the “TZ database name” format of it - list of timezones. The timezone is not dynamic but will always load the time of one certain place no matter what is the timezone of the visitor’s device.

Setting the time conditions

The script below is set to hide the chat widget if some certain conditions are not met.

    <script>
function onReady(initialData) {
if ((lcday != "Saturday" && lcday != "Sunday") && (lchour >= 9 && lchour < 17)) {
console.log("Office time - chat displayed");
} else {
console.log("Out of office time - chat hidden");
LiveChatWidget.call("hide");
}
}
LiveChatWidget.on("ready", onReady);
</script>

There are 2 main conditions day and hours.

  • day - (lcday != "Saturday" && lcday != "Sunday") - The lcday variable value is the current time in the specified timezone. The conditions is met if its value is not (represented by !=) Saturday and (represented by &&) at the same time is also not Sunday. You could add more excluded days if needed.
  • time - (lchour < 17 && lchour >= 9) - The lchour variable value represent only the current hour without minutes. If it is 5:37PM in the chosen timezone, the value will be 17 (24h hour clock). The example time conditions are set to reflect the 9 to 5 working day - it checks if the hour is lower than 17 and if it is more or equal 9. This setup will make the conditions to not be met at 8:59AM (hour is 8) or at 5:03PM (hours is 5).

Our example condiitons display the chat widget only from Monday to Friday between 9AM and 5PM. Feel free to modify them according to your office hours! The best practice would be to add both scripts above your LiveChat chat widget snippet code (as separate scripts).

And that's all!

If you have any questions, let us know!

Yours, LiveChat Team <3