Advanced Javascript & CSS Usage

Back to Documentation

JavaScript Functions

SwapTopic exposes several global JavaScript functions that allow you to interact with the personalization engine programmatically.

Conversion Tracking

swapTopicTrackConversion();

Manually triggers a conversion event. Use this when you want to track conversions on actions that don’t involve page navigation.

User Data Management

// Get all SwapTopic data
const userData = swapTopicGetData();

// Update specific fields
swapTopicSetData({
  visits: 5,
  converted: true
});

// Reset all data
swapTopicResetData();

Segment Management

// Add a segment
swapTopicAddSegment('enterprise');

// Check if user has a segment
if (swapTopicHasSegment('enterprise')) {
  // Show enterprise-specific features
}

// Remove a segment
swapTopicRemoveSegment('enterprise');

// Clear all segments
swapTopicClearSegments();

// Get all user segments
const segments = swapTopicGetSegments();

URL Parameters

SwapTopic responds to several URL parameters:

  • ?addsegment=segment1,segment2 – Add segments to user
  • ?removesegment=segment1,segment2 – Remove segments from user

CSS Classes

SwapTopic adds CSS classes to personalized elements and the <body> tag:

Element Classes

/* Elements that have been personalized */
.swaptopic-personalized {
  /* Your custom styles */
}

/* Elements with specific rule types */
.swaptopic-first-time { }
.swaptopic-returning { }
.swaptopic-converted { }
.swaptopic-query-utm_source-google { }
.swaptopic-visits-2-plus { }
.swaptopic-segment-enterprise { }
.swaptopic-not-segment-free-trial { }
.swaptopic-referrer-google-com { }

Body Classes

The highest priority matching rule adds its class to the <body> tag, enabling you to style multiple elements based on the active personalization:

/* Target all elements when visitors are returning */
body.swaptopic-returning .special-element {
  display: block;
}

/* Special styling for users from specific referrers */
body.swaptopic-referrer-google-com .header {
  background-color: #4285F4;
}

API Integration

Custom JavaScript can be used to integrate SwapTopic with other tools:

// Track conversion in Google Analytics and SwapTopic
document.getElementById('signup').addEventListener('click', function() {
  // Track with GA
  gtag('event', 'conversion', {'send_to': 'AW-123456789/AbC-D_efG-h12_34-567'});

  // Track with SwapTopic
  swapTopicTrackConversion();
});

Custom Event Handling

// Apply personalization after dynamic content loads
function loadMoreContent() {
  // Load new content via AJAX
  fetch('/api/content')
    .then(response => response.json())
    .then(data => {
      document.getElementById('dynamic-content').innerHTML = data.html;

      // Force SwapTopic to scan new elements
      SwapTopic.processExistingNodes();
    });
}