JS API – window.w2w object

The w2w object provides a collection of utility methods for managing user interface interactions, analytics, navigation, and user properties in web applications.

Table of Contents


UI Methods

showToast

Shows a toast notification message to the user.

Syntax:

w2w.showToast(message, type, time)

Parameters:

  • message (string): The message text to display in the toast
  • type (string, optional): The type of toast. Default: 'success'. Available types: 'success', 'error'
  • time (number, optional): Duration in seconds to show the toast. Default: 10

Example:

// Show success toast for 5 seconds
w2w.showToast("Operation completed successfully!", "success", 5);

// Show error toast with default duration
w2w.showToast("Something went wrong", "error");

// Show default toast
w2w.showToast("Hello World!");

Notes:

  • The toast will automatically hide after the specified time
  • Line breaks in the message (\n) are converted to HTML <br> tags
  • Logs a 'Show toast' analytics event

hideToast

Manually hides the currently displayed toast notification.

Example:

// Hide any currently displayed toast
w2w.hideToast();

showPopup

Shows a modal popup with a title, HTML content, and action buttons.

Syntax:

w2w.showPopup(config)

Parameters:

  • config (object):
    • title (string, optional): Header text displayed at the top of the popup
    • content (string, optional): HTML content for the popup body
    • buttons (array, optional): Array of button objects:
      • text (string): Button label
      • action (function|string|array, optional): Callback executed on click. Can be a single function, a string of JS code, or an array of actions executed in order
      • class (string, optional): CSS class for the button. Default: 'w2w-popup__btn-primary'. Use 'w2w-popup__btn-secondary' for a secondary style
    • popupClass (string, optional): Extra CSS class appended to the modal wrapper

Example:

w2w.showPopup({
  title: 'Save Changes',
  content: '<p>Do you want to save your changes?</p>',
  buttons: [
    { text: 'Cancel', action: () => w2w.hidePopup(), class: 'w2w-popup__btn-secondary' },
    { text: 'Continue', action: [() => saveData(), () => w2w.hidePopup()] }
  ]
});

Notes:

  • Creates a #popup-overlay element on first use and reuses it for subsequent popups
  • Button actions can be functions, strings evaluated as JS, or arrays of mixed actions
  • See also: Show custom popup with JS

hidePopup

Closes the currently displayed popup and clears its content.

Example:

w2w.hidePopup();

showFullscreenOverlay

Displays a fullscreen overlay with custom HTML content.

Syntax:

w2w.showFullscreenOverlay(html, time, callback)

Parameters:

  • html (string): The HTML content to display in the overlay
  • time (number, optional): Duration in seconds to show the overlay. Default: 3
  • callback (function|string, optional): Function to execute when overlay closes, or function string to evaluate

Example:

// Show overlay for 5 seconds with callback
w2w.showFullscreenOverlay(
  "<h1>Welcome!</h1><p>This is a fullscreen message</p>",
  5,
  function() {
    console.log("Overlay closed");
  }
);

// Show overlay with default duration
w2w.showFullscreenOverlay("<div class='loading'>Loading...</div>");

copyToClipboard

Copies text to the user's clipboard.

Syntax:

w2w.copyToClipboard(text, callback)

Parameters:

  • text (string): The text to copy to clipboard
  • callback (function, optional): Function to execute after successful copy

Example:

// Copy with callback
w2w.copyToClipboard("Hello World!", function() {
  console.log("Text copied successfully!");
});

// Copy without callback
w2w.copyToClipboard("Some text to copy");

User Properties Methods

get

Retrieves a user property from window.user_properties.

Syntax:

w2w.get(key, defaultValue)

Parameters:

  • key (string): The property name
  • defaultValue (any, optional): Value returned when the property is missing. Default: ''

Example:

const userId = w2w.get('user_id', '');
const email = w2w.get('email', '[email protected]');
const answers = JSON.parse(w2w.get('quiz_answers', '{}'));

Notes:


set

Alias for setUserProperty. Saves a value to user properties and sends it to analytics backends.

Syntax:

w2w.set(key, value, callback)

Parameters:

  • key (string): The property name
  • value (any): The property value
  • callback (function, optional): Function executed after the property is saved

Example:

w2w.set('api_response', JSON.stringify(data));

w2w.set('score', 95, function() {
  console.log('Score saved');
});

setUserProperty

Sets a user property for analytics tracking.

Syntax:

w2w.setUserProperty(key, value, callback)

Parameters:

  • key (string): The property name
  • value (any): The property value
  • callback (function, optional): Function to execute after setting the property

Example:

// Set user property with callback
w2w.setUserProperty("user_level", "premium", function() {
  console.log("Property set successfully");
});

// Set user property without callback
w2w.setUserProperty("last_login", new Date().toISOString());

setUserProperties

Sets multiple user properties at once for analytics tracking.

Syntax:

w2w.setUserProperties(properties, callback)

Parameters:

  • properties (object): An object containing key-value pairs of properties to set
  • callback (function, optional): Function to execute after all properties are set

Example:

// Set multiple user properties with callback
w2w.setUserProperties({
  user_level: "premium",
  subscription_type: "annual",
  favorite_color: "blue",
  age: 25
}, function() {
  console.log("All properties set successfully");
});

// Set multiple properties without callback
w2w.setUserProperties({
  last_login: new Date().toISOString(),
  visit_count: 5,
  has_purchased: true
});

Notes:

  • This method is more efficient than calling setUserProperty multiple times
  • All properties are sent in a single batch request to the backend
  • The method updates analytics platforms including Amplitude, PostHog, and Mixpanel
  • Properties with key 'email' are handled specially and stored in a cookie

Analytics Methods

logEvent

Logs an analytics event using the AnalyticsManager.

Syntax:

w2w.logEvent(event, event_properties, options)

Parameters:

  • event (string): The name of the event to log
  • event_properties (object, optional): Additional properties/data associated with the event
  • options (object, optional): Extra logging options passed to AnalyticsManager

Example:

// Log simple event
w2w.logEvent("Button Clicked");

// Log event with properties
w2w.logEvent("Purchase Completed", {
  product_id: "123",
  price: 29.99,
  currency: "USD"
});

addGlobalEventProperty

Adds a property that is automatically attached to every subsequent analytics event.

Syntax:

w2w.addGlobalEventProperty(property, value)

Parameters:

  • property (string): The property name
  • value (any): The property value

Example:

w2w.addGlobalEventProperty('campaign_id', 'summer_sale');
w2w.addGlobalEventProperty('source', 'custom_checkout');

// All later w2w.logEvent() calls include campaign_id and source
w2w.logEvent('Purchase Completed', { price: 29.99 });

Notes:

  • Properties persist for the current page session until overwritten
  • Useful for tagging a batch of events with shared context (campaign, funnel step, payment provider, etc.)

onEvent

Registers an event listener for analytics events.

Syntax:

w2w.onEvent(eventName, callback)

Parameters:

  • eventName (string): The name of the event to listen for, or "*" to listen to all events
  • callback (function): The function to execute when the event is triggered

Callback Parameters:

  • For specific events: callback(eventProperties) - receives the event properties object
  • For wildcard "*" events: callback(eventProperties, eventName) - receives both the event properties and the event name

Example:

// Listen for purchase events
w2w.onEvent("Purchase", function(eventProperties) {
  console.log("Purchase detected:", eventProperties);
});

// Listen for page view events
w2w.onEvent("PageView", function(eventProperties) {
  console.log("Page viewed:", eventProperties);
});

// Listen to all events using wildcard
w2w.onEvent("*", function(eventProperties, eventName) {
  console.log("Event fired:", eventName, eventProperties);
});

Notes:

  • Use "*" as the eventName to listen to all events
  • Wildcard listeners receive both eventProperties and eventName as parameters
  • Multiple listeners can be registered for the same event
  • Listeners are executed before the event is sent to analytics platforms

onSet

Registers a listener for when user properties are set.

Syntax:

w2w.onSet(property, callback)

Parameters:

  • property (string): The name of the property to listen for, or "*" to listen to all property sets
  • callback (function): The function to execute when the property is set

Callback Parameters:

  • callback(value, key) - receives the property value and the property key

Example:

// Listen for when email is set
w2w.onSet("email", function(value, key) {
  console.log("Email was set to:", value);
});

// Listen for when subscription_id is set
w2w.onSet("subscription_id", function(value, key) {
  console.log("Subscription ID was set to:", value);
});

// Listen to all property sets using wildcard
w2w.onSet("*", function(value, key) {
  console.log("Property set:", key, "=", value);
});

Notes:

  • Use "*" as the property to listen to all property sets
  • The callback receives both the value and key parameters
  • Listeners are triggered for both setUserProperty and setUserProperties methods
  • Multiple listeners can be registered for the same property

Navigation Methods

moveToNextScreen

Moves to the next screen in the application flow.

Syntax:

w2w.moveToNextScreen(isSkipInEditMode)

Parameters:

  • isSkipInEditMode (boolean, optional): When true and the page is opened in edit mode (?edit_mode=1), navigation is skipped and a toast is shown instead

Example:

// Move to the next screen
w2w.moveToNextScreen();

// Skip navigation in quiz editor preview
w2w.moveToNextScreen(true);

moveToScreen

Moves to a specific screen by its ID.

Syntax:

w2w.moveToScreen(screen_id)

Parameters:

  • screen_id (string): The ID of the screen to navigate to

Example:

// Move to screen with ID "welcome"
w2w.moveToScreen("welcome");

// Move to screen with ID "section1"
w2w.moveToScreen("section1");

moveToPreviousScreen

Moves to the previous screen in the application flow.

Example:

// Move to the previous screen
w2w.moveToPreviousScreen();

Unit Conversion (w2w.units)

The w2w.units object exposes height, weight, and BMI helpers used by dimension blocks. Useful in custom JS calculations.

Methods:

MethodDescription
setUnitSystem(name)Sets 'metric' or 'imperial' and saves user_units_system
feetInchesToCm(feet, inches)Converts feet/inches to centimeters
cmToFeetInches(cm)Returns { feet, inches, text }
lbsToKg(lbs)Pounds to kilograms
kgToLbs(kg)Kilograms to pounds
calculateBMI(weight, height, weightUnit, heightUnit)BMI from weight/height with unit conversion
getBMILevel(bmi)Returns 'underweight', 'normal', 'overweight', or 'obese'
getBMILevelWithDescription(bmi)Returns { level, description, bmi }
calculateBMIWithFeetInches(weight, feet, inches, weightUnit)BMI when height is given as feet + inches

Example:

const cm = w2w.units.feetInchesToCm(5, 11);
const bmi = w2w.units.calculateBMI(180, cm, 'lbs', 'cm');
const info = w2w.units.getBMILevelWithDescription(bmi);
w2w.setUserProperty('user_bmi', info.bmi);

Utility Methods (w2w.utils)

capitalizeFirstLetter

Capitalizes the first character of a string.

w2w.utils.capitalizeFirstLetter('hello'); // "Hello"

formatCurrency

Formats a number as currency using Intl.NumberFormat.

w2w.utils.formatCurrency(29.99, 'USD', 'en-US'); // "$29.99"
w2w.utils.formatCurrency(1990, 'EUR', 'de-DE');  // "1.990,00 €"

Parameters: value, currency (default 'USD'), locale (default 'en-US')

transliterate

Transliterates non-Latin text to Latin characters. Handles Cyrillic, German umlauts, Hebrew, Arabic, Thai, Hindi, and strips remaining diacritics.

w2w.utils.transliterate('Привет');  // "Privet"
w2w.utils.transliterate('Zürich');  // "Zurich"
w2w.utils.transliterate('東京');     // unchanged if no mapping exists

Usage Notes

  • All methods are available globally through the window.w2w object
  • The object integrates with the application's analytics system (AnalyticsManager)
  • Navigation methods work with the application's screen management system (screensManager)
  • Toast, popup, and overlay methods manipulate DOM elements created at runtime (#toast, #popup-overlay, #fullscreen-overlay)
  • w2w.get() / w2w.set() are shorthand helpers for reading and writing user properties in custom JS