javascripthtmlcsslivechat

Hide div if agents offline with Live Chat Inc


I am using LiveChat on my website and trying to show a div if no agents are available, using their guide here

Javascript

LC_API.on_after_load = function() {
    if (LC_API.agents_are_available()) {
        $("#ChatLink2").hide(); 
    } else {
        $("#ChatLink2").show();    
    }   
};

HTML

<div class='ChatLink2' id='ChatLink2'>Currently Unavailable</div>

However, the div ChatLink2 is not showing when no agents are available


Solution

  • It appears to be race conditions with both LiveChat and JQuery. Below checks for LC availability and uses vanilla JS instead of jQuery.

    Also included state change callback if agents go offline after init.

    var waitForLC = setInterval(function () {
        if (window.LC_API === undefined) {
            return;
        }
        clearInterval(waitForLC);
        var showUnavailableStatus = function(show){
            var statusDiv = document.getElementById("ChatLink2");
            var style = show ? "block" : "none";
            statusDiv.style.display = style;
        }
        LC_API.on_after_load = function() {
            if (LC_API.agents_are_available()) {
                showUnavailableStatus(false);
            } else {
                showUnavailableStatus(true);
            }
        };
        LC_API.on_chat_state_changed = function(data) {
            showUnavailableStatus(data.state==="offline");
        };
    }, 100);