Javascript code to add a click to a button

Hi. Apologies for the newbie question! I was reading the Chat API docs and wanted to try adding this script to a website button or link.

document.selectElementById(‘contact-button’).addEventListener(‘click’,function() {
LeadBooster.trigger(‘open’);
});

I’ve tried to get it to work, but onclick the chatbot does not open. Can you spot any issues with my code?

<button id="123-123" onclick="doSomething()">Ask a question</button>
<script>
function doSomething() {
document.selectElementById('123-123').addEventListener('click',function() {
LeadBooster.trigger('open');
}
}
</script>

Any tips much appreciated.

Hello!

Theres two things:

  • selectElementById method does not exist on document in Javascript :slight_smile:
  • the way it is done now it only attaches the event listener on the onclick, i guess thats definitely not what you wanted to do

My suggestion (tested and it works):

<button id="chatbot-trigger-button">Ask a question</button>
      <script>
        (function attachOnClickChatbotTrigger() {
          document
            .getElementById('chatbot-trigger-button')
            .addEventListener('click', function () {
              LeadBooster.trigger('open');
            });
        })();
      </script>

Let me know if that worked! :slight_smile: Have a nice day.

Rosta Klein
developer at Pipedrive

2 Likes

Hey, that’s great! Thank you for your help. Off to create buttons galore! :wink: