Rich-text Reply

Possible to replace inline JS/jQuery script in control to create variation?

JulienLN 02-12-15

Possible to replace inline JS/jQuery script in control to create variation?

Hi, and my apologies in advance if this is kind of a stupid question...


The issue I'm facing is the following: I want to modify the text of a button in a page to create a variation to test. This text is adjusted dynamically using inline JS / jQuery included in the page, based on whether a checkbox is checked or not.


I have located the JS / jQuery code that is doing this and can modify it to do what I want. But I don't know how to use Optimizely to replace it so that I can create a variation to test.


I have searched Optiverse and the doc for an answer on this, but can't seem to find any, which leads me to believe that my whole approach may be flawed...


Is replacing an inline script possible at all using Optimizely, like we can replace HTML / CSS?


Many thanks!


Best regards,
- Julien

Level 2

Re: Possible to replace inline JS/jQuery script in control to create variation?

Hey Julien,


If you're saying that you can modify the inline script/code on the site that dynamically changes the button's text, then you could definitely create a custom event that gets fired whenever this occurs. Then, in your Optimizely variation JS, you could listen for this event, and when it occurs, handle your logic accordingly. For example, here's a way this could be done with vanilla JavaScript:


    // Attach a click event listener to the <body> element

    var b = document.body;


    // For this example, let's add a click event listener to

    // the <body> element that fires a custom event you create

    b.addEventListener('click', function() {

        // create a new event with a custom name

        var e = new Event('your_custom_event_name');

        // now "dispatch" (i.e. trigger) this event

        b.dispatchEvent(e); // dispatching `e`, the event just created



    // Now set a listener on the <body> element such

    // that when the 'your_custom_event_name' event fires,

    // you handle it accordingly (run some code)

    b.addEventListener('your_custom_event_name', function() {
        // Do stuff, for example:

        console.log('custom event fired!');

        // So, change button text in variation JS here...




So, in this example, you actually dispatch a custom event via the inline JS/jQuery code that originally changes the button's text within the website (NOT Optimizely). Then, in Optimizely, you listen for this event in whatever variation you need, and when it fires, you do stuff specific to that variation.


Let me know if this doesn't quite answer what you're asking...


-- Sean
UI Developer @ Blue Acorn

optimizely developer certification