Search code examples
javascripthtmldynamic-htmldynamic-script-loadinggoogle-optimize

Insert dynamic onClick event script in Google Optimize


I need to add a html element, a button, trough the Google Optimize experiment and it has to perform a certain script depending on the experiment.

I have tried to do it in the following ways:

<button id="my-button">Show</button>


var script = document.createElement('script');
var inlineScript;
script.appendChild(inlineScript); 
element.appendChild(script);

the content of inlineScript variable:

1.
    'document.createTextNode('document.addEventListener("click",function(e){ if(e.target && e.target.id== "my-button"){ console.log("test"); } }); );');'


2.
    'document.createTextNode('var myButtonElement = document.getElementById(
    "my-button");
    myButtonElement.addEventListener("click", function()
    { console.log("test");});')'

However neither approach works. When I hardcode the code from backend it works fine, but it needs to be added dynamically trough Optimize. Is there another way to add a dynamic html script to the html?


Solution

  • It is possible, that there is a way to do this with the sole usage of Google Optimize tool, however I was unable to do so.

    In order to solve this problem I have defined a function and a variable that is set in the head in the CMS tool, and then in the optimize I just do the following:

    1. A button with myFunction
    2. A script appended to an element to set the variable with a value I need:
    var script = document.createElement('script');
    var inlineScript = document.createTextNode("myValue= '123'");
    element.appendChild(script);