Skip to main content
menu_icon.png

Everything you need to switch from Optimizely Classic to X in one place: See the Optimizely X Web Transition Guide.

x
Optimizely Knowledge Base

Shared code: Run custom JavaScript and CSS across all variations

This article is about Optimizely X. If you're using Optimizely Classic, check this article out instead.
 
relevant products:
  • Optimizely X Web Experimentation
  • Optimizely X Web Personalization

THIS ARTICLE WILL HELP YOU:
  • Execute JavaScript across all variations in an experiment
  • Apply CSS across all variations in an experiment

With Optimizely, you have the flexibility to add your own customized JavaScript or CSS code to your experiments. You can apply this custom code at the variation level, or you can use Optimizely's shared code feature to apply it to an entire experiment, across all variations.

Some common use cases for shared JavaScript code in Optimizely include:

  • Sending Optimizely information to your analytics service.
  • Adding API calls for custom events.
  • Adding functions that can be used across multiple variations, and calling them with different parameters in the variation code.

For example, the code below sends a custom event API call when visitors scroll to a certain depth:

As another example, by typing this JavaScript code into the shared code box, you would create an alert containing any string value:

window.bringUpAlert = function(value) {
  alert("You are in " + value);
};

Then, in the custom code for a particular variation, you could just call the function with the value of your choice:

bringUpAlert("Variation #1")

Shared CSS lets you define CSS properties of brand new content on the page without having to write it inline.

Shared CSS affects all variations, so modifying the CSS of an existing class or element will cause all the variations (including the original page) to display the new style or behavior.

Many Optimizely users commonly use shared CSS to define new classes, and then use those classes to either create new content or modify existing elements by adding those classes.

For example:

This code defines a class called purchaseForm, which sets a background-image property for whatever element it is assigned to. It also defines the hover state of that class. You could use this CSS to create a rollover in your variations.

Add custom JavaScript or CSS to an experiment's shared code

Adding shared code is a straightforward task. From your experiment's dashboard, click Shared Code.

Next, in the Shared Code dashboard, click on either the Javascript or CSS tab, depending on which type of code you're adding.

Now just type or paste your code into the text window and click Save & Apply, or click Revert to Saved to discard your changes and start over. 

Related articles

Custom code in Optimizely X