The JavaScript variant type in Compose serves as a dynamic tool, offering a flexible approach for implementing subtle changes when A/B testing. This article delves into the versatility of the JavaScript variant type, showcasing its ability to modify styles or alter copy. Through real examples, we explore how to leverage the JavaScript variant to enact changes on a site. Understanding and using this variant type will open the door to endless experimentation.
When using the JavaScript variant type, it is important that the code is executed immediately when the variant is triggered. To make sure of this, we are using an Immediately-Invoked Function Expression (IIFE). The general pattern of this is:
(() => {
// your code
})();
Button copy example
This variant type is generally used for testing specific element changes on a page. For example, changing the copy on a button might use the following code:
(() => {
const updateButton = () => {
const button = document.getElementById("my-button")
if (button) {
button.textContent = "Shop Now!"
} else {
requestAnimationFrame(updateButton)
}
}
updateButton()
})();
The code document.getElementById() will look for the element with the ID "my-button" and store it in 'button'. Then we say, if 'button' exists, change the button text to "Shop Now!". Otherwise, we use requestAnimationFrame() to say that the next time the page repaints, run updateButton first to see if we need to change the copy.
Button styling example
Another example is changing the style of a button with the following code:
(() => {
const style = document.createElement('style')
style.textContent = `
#my-button {
background-color: forestgreen;
}
`
document.head.append(style)
})();
In this code, document.createElement('style') is creating a new <style> element. Then we specify with CSS that we want the element with the ID 'my-button' to have the background color of forestgreen. Then we append that style tag to the <head> so that our specified styles are shown on the page.
As you can see, the JavaScript variant type plays a pivotal role in A/B testing. We hope this helps create meaningful experiments that allow you to elevate the user experience and maximize conversions.