Skip to content
Advertisement

Firing JavaScript generated link issue

I have issues firing this link (that triggers a script from Chargebee) when is added dynamically via JavaScript. When it’s added directly in html it works normally.

The entire generated link is appearing correctly (populated with the variants) in browser when inspected just it doesn’t fire.

Here are the pieces I have related to this:

The JavaScript part:

var checkout = document.getElementById("checkout");
         
var link = '<a href="javascript:void(0)" data-cb-type="checkout"' + data-cb-1 + data-cb-2 + data-cb-3'>Order</a>';
 
checkout.innerHTML = link;

A simple div:

<div id="checkout"></div>

The script from chargebee:

<script src="https://js.chargebee.com/v2/chargebee.js" data-cb-site="site-name"></script>

Advertisement

Answer

Once you’ve loaded chargebee.js script it starts to look for a tag a with specific data-cb attributes. The script does it one time only. If the tag a did not exist in the DOM then, the script does nothing. When you add the tag a later that makes no effect at all, because a “discovery phase” is over.

If you want to have more control over chargebee initialisation process, you should go for “Checkout via API” option provided by the developers.

P.S. There are two hacky solutions:

  1. You may load Chargebee script after adding tag a to the DOM.
function loadChargebee() {
    var script = document.createElement("script");
    script.src = "https://js.chargebee.com/v2/chargebee.js";
    script.type = "text/javascript";
    document.getElementsByTagName("head")[0].appendChild(script);
}

var checkout = document.getElementById("checkout");
         
var link = '<a href="javascript:void(0)" data-cb-type="checkout"' + data-cb-1 + data-cb-2 + data-cb-3'>Order</a>';
 
checkout.innerHTML = link;

loadChargebee(); // <=== add Chargebee.js

  1. Leave the tag a in the DOM, load the script as usual but modify data attributes as needed after page load:
<a id="beecheckout" href="javascript:void(0)" data-cb-type="checkout" data-cb-1="" data-cb-2="" data-cb-3="">Order</a>

document.getElementById('beecheckout').setAttribute('data-cb-1','new data value');

Advertisement