It is useful to set up re-useable variables and methods that individual variants can utilize when creating an experiment.
This D.R.Y. (Don’t Repeat Yourself) approach to experiment development is more efficient than copying commonly used variables and methods between variants.
Common code is added at the Web Editor’s context level and is available to all of that context's variants. If you want to use common (or shared) code across an entire project, check out Project Dependency Imports.
Below is an example of common code and how a variant can access it for its own use.
Common code example
The following JavaScript function creates a new DOM element. Add it to the JavaScript field in the context and you can access it within that context's variants.
// Context-level JavaScript
if (!window.evolv.customer) {
window.evolv.customer = {};
}
if (!window.evolv.customer.createElement) {
window.evolv.customer.createElement = function (type, id, classes) {
var el = document.createElement(type);
el.setAttribute('id',id);
classes.forEach(function(c) {
el.classList.add(c);
});
return el;
}
}
To use this code in a variant you can reference the global variable.
var el = evolv.customer.createElement('span','my-new-span',['one-class','another-class']);