Opening your ChatBox with a custom trigger

Frontend and Tutorials

Thumb1400

It's pretty easy to start a chat with the Natterly ChatBox, just click the chat tray and the ChatBox will spring open ready for your customer to send you a message. Sometimes however, that might not be enough. Perhaps you want to have a large button on your page saying "Click here to chat with us now!", or a link for support in your navigation bar that pops the ChatBox open when clicked.

If this sounds like something you'd like to acheive, then this is the tutorial for you!

Getting started

To start with, you'll need to have the Natterly ChatBox set up on our page, follow the directions outlined in our embed Natterly on your website documentation to get set up in no time.

Once that's done, you should have some JavaScript on your page that looks something like this:

var chatbox = new NatterlyChatbox('<YOUR SITE TOKEN>');
chatbox.render();

Keeping it simple

If you want to keep things as simple as possible you can simply inline the JavaScript to open the chatbox into the onclick attribute of the button. The function we need to open the chatbox is chatbox.open().

<button onclick="chatbox && chatbox.open()">
  Chat with us
</button>

With this code, each time the button clicked we check if the chatbox exists. If it does, we call chatbox.open().

This method is very simple but it does come with some limitations. For example, if there are no agents available to chat then the ChatBox will not display for your users, rendering your button useless. If you want to take these edge cases into account, then read on!

A more comprehensive solution

Listening for the click event

In order to open the chat when a button is clicked, we are going to have to add an event listener to the button, and tell Natterly that every time that event listener is triggered, the ChatBox should be opened.

First, let's create the button somewhere on our page:

<button id="button">Start a chat with us!</button>

We've created a button and given it an ID of button, this ID will help us store the element in a variable and add our event listener. You can call it whatever you like!

So, back to our JavaScript. Underneath our existing code we want to store our button element in a variable and add the event listener:

// Our existing code
var chatbox = new NatterlyChatbox('<YOUR SITE TOKEN>');
chatbox.render();

// Store the button in a variable
var button = document.getElementById("button");
// add an event listener for the click event
button.addEventListener("click", function(event) {
    // the code in here will be run whenever the button is clicked.
});

Now we have the event listener set up, we need to write the code for the event listener callback function, which will be run each time the button is clicked. This function needs to do two things.

1) Prevent the default event from firing - if the button was a link, for example, we want to prevent the link from navigating away from the page.

2) Actually open the ChatBox. We can use the handy chatbox.open() function for this

var button = document.getElementById("button");
button.addEventListener("click", function(event) {
    // First prevent the default event
    event.preventDefault();
    // then, open the chatbox
    chatbox.open();
});

Nice! Now when you click on the button, the ChatBox should open!

Hiding the button when the ChatBox is not available

The Natterly ChatBox will only display on your page when there are agents online and ready to chat. This presents us with a problem: what about when the ChatBox is not available? Our button won't work anymore, oh no!

To get around this, we can hide the button, and only show it if the ChatBox is available. First, we need to hide the button by default. You could either add a CSS rule to your stylesheet for the button, or just add the CSS to hide it inline in the HTML:

<button id="button" style="display: none;">
    Start a chat with us!
</button>

Now the button is hidden. What we need to do next is show the ChatBox only when it is available. We can check if the ChatBox is available using chatbox.available, the problem is, that this doesn't update until after the ChatBox has connected to our server. To get around this we need add another event listener that fires when the ChatBox connects.

The ChatBox comes with a number of events that you can read about in our advanced options for web developers documentation. The one that we are interested in here is the "SessionJoined" event, which fires when the ChatBox connects to the server.

// Listen for the Chatbox connecting to the server
chatbox.client.on("SessionJoined", function() {
    // We are now connected, check if the chatbox is available
    if (chatbox.available) {
      // The chatbox is available! Show the button
      button.style.display = "inline-block";
    }
});

Now when the ChatBox successfully connects to the server the button will reveal itself ready for your users to click! If the ChatBox is not available, then it will remain hidden, and your users won't be confused by a button that doesn't work.

Updating the button as availability changes

The Natterly ChatBox is very smart, if an agent becomes available while a user is browsing the page, then the ChatBox's availability will update in real-time, and it will reveal itself to the user. The problem here is that we have hidden the button, and now the ChatBox is available again! You may be ok with this happening, but if you want the button to reveal itself alongside the ChatBox, you can hook into another Natterly Chatbox event - "SiteAvailability".

The "SiteAvailability" event is fired whenever the ChatBox's availability changes. We can use it to hide or show our ChatBox opening button as and when the ChatBox becomes available.

// Listen for the availability changing
chatbox.client.on("SiteAvailability", function(data) {
    if (data.available) {
      // if the Chatbox is available then show the button
      button.style.display = "inline-block";
    } else {
      // otherwise, hide the button
      button.style.display = "none";
    }
});

Now the button will hide and show itself as the availability of your agents change. Pretty neat!

A different approach to handling availability changes

Depending on your site layout, a button appearing and disappearing as the availability changes may not look the best. If you'd rather always show the button, and instead handle the case where a user tries to open a chat when there is no availability you can do that too, by passing a callback to the chatbox.open() function. We can ammend our button's click handler to handle this:

button.addEventListener("click", function(event) {
    event.preventDefault();
    // this time we pass a callback function.
    // The function takes one argument, an array of errors
    chatbox.open(function(errors) {
      // if there are no errors, no worries, exit the function
      if (!errors) return;
      // otherwise, we need to check if the errors include an `unavailable` error
      var unavailable = errors.filter(function(err) {
        return err["unavailable"];
      });
      // if there is an unavailable error then we can can do something to notifiy our user
      if (unavailable.length) {
        alert("Sorry, we have no agents available to chat right now.")
      }
    });
});

Now instead of hiding the button when the ChatBox is unavailable, we simply alert the user that it is unavailable.

The only other error you are likely to get from this function is an alreadyOpen error, which you will get if you try to open a ChatBox that is already open. You can safely ignore this error if you want to.

Review

To conclude, here is the complete code for this tutorial. Use it and customize it to your own needs on your site to get your Natterly ChatBox working exactly how you want it!

<button id="button" style="display: none;">
    Start a chat with us!
</button>
var chatbox = new NatterlyChatbox('<YOUR SITE TOKEN>');
chatbox.render();

var button = document.getElementById("button");

button.addEventListener("click", function(event) {
    event.preventDefault();
    chatbox.open(function(errors) {
      if (!errors) return;
      var unavailable = errors.filter(function(err) {
        return err["unavailable"];
      });
      if (unavailable.length) {
        alert("Sorry, we have no agents available to chat right now.")
      }
    });
});

chatbox.client.on("SessionJoined", function() {
    if (chatbox.available) {
      button.style.display = "inline-block";
    }
});

chatbox.client.on("SiteAvailability", function(data) {
    if (data.available) {
      button.style.display = "inline-block";
    } else {
      button.style.display = "none";
    }
});

A little bit about the author

I’m Ben, one of the front end developers here at aTech Media. When I’m not in front of the computer coding you’ll find me building my next gaming PC, watching Formula 1, or climbing a mountain... Occasionally.