Optimizely A/B test service uses .replaceWith("new HTML") extensively to produce easy A/B testing. This has the side effect of removing any event listeners that were listening to events from the replaced elements, even if the new elements would have same IDs/classes.
Example:
- DOM contains: - <div class="something"> <button id="myButton"></button> </div>
- Listened by: - $("#myButton").click(function() { console.log('clicked!'); });
- Replaced by: - $(".something").replaceWith("some new HTML, containing #myButton");
After step 3, hitting the #myButton does not work anymore, as the original DOM element was destroyed and a new one added.
What would be a good and "clean" way to solve this issue ?
Possible solutions
- Know your codebase and "re add" the appropriate event listeners in Optimizely's experiment.
- problem: A/B testers might not be real software devs, think this is a hassle.
- does not seem like a very clean way
 
- Find a way to execute code after Optimizely, add all event listeners that way. Is there a good way to do this ? 
- Use "event delegation using $.on()" as described here: how to replace HTML with jQuery but keep event bindings - problem: hard to predict what exactly will be A/B tested and replaced
 
Edit: I am using jQuery 1.11.x
 
     
     
    