Solved

problem adding custom trigger to klaviyo form


Userlevel 1
Badge +5
  • Active Contributor I
  • 10 replies

I want to show/hide forms based on the traffic source.

I have worked through Bing Chat and ChatGPT to generate the code sample, and I am certain it’s working.

However, I have a question: can I use Google Tag Manager to add the custom JS code and set the form to fire across all pages, or do I have to manually add it to individual pages?

My store runs on Shopify, FYI

icon

Best answer by Taylor Tarpley 18 May 2023, 01:00

View original

4 replies

Userlevel 7
Badge +60

Hi there @bhas

 

Thanks for your question! 

 

Another fellow Community member, @furnaceX, was also interested in creating a custom show/hide form!

 

I’m going to run this by some of our engineers to confirm whether or not this is possible and will report back when I have an answer! 

 

Thanks for participating in the Community!

-Taylor 

Userlevel 1
Badge +5

Hi @Taylor Tarpley 

When you are loading forms using custom triggers, you have to select the “Only show form based on custom triggers” under the Display Timing section in Targeting and Behavior settings as per this article, correct?

So, I got AI to create this code that will show and hide forms based on traffic source, but also includes standard rules that you would normally set from the “Display according to rules” option, like when can a form show up or which pages it should not. 

I installed it in the theme.liquid file in Shopify just before </head>.

However, none of the forms showed up on testing. 

Could you please run this code-snippet by your engineers to check for any issues?
 

// Define a function to check if the current URL contains /checkouts or /orders
function isCheckoutOrOrderPage() {
// Get the current URL
var currentUrl = window.location.href;
// Convert the current URL to lowercase
currentUrl = currentUrl.toLowerCase();
// Define a regular expression pattern to match /checkouts or /orders
var checkoutOrOrderPattern = /\/(checkouts|orders)\//i;
// Return true if the current URL matches the pattern, false otherwise
return checkoutOrOrderPattern.test(currentUrl);
}

// Define a function to show the form based on the referrer and the device type
function showFormBasedOnReferrerAndDevice() {
// Get the referrer URL or use an empty string as a fallback
var referrer = document.referrer || '';
// Convert the referrer to lowercase
referrer = referrer.toLowerCase();

// Define the form IDs for different traffic types and device types
var formIdForNiftTrafficDesktop = 'your-popup-form-id-for-nift-traffic-desktop';
var formIdForNiftTrafficMobile = 'your-popup-form-id-for-nift-traffic-mobile';
var formIdForOtherTrafficDesktop = 'your-popup-form-id-for-other-traffic-desktop';
var formIdForOtherTrafficMobile = 'your-popup-form-id-for-other-traffic-mobile';

// Define a regular expression pattern to match the referrer URL
var niftPattern = /nift/i;

// Define a variable to store the form ID based on the referrer and the device type
var formId;

// Check if the referrer URL matches the nift pattern
if (referrer.match(niftPattern)) {
// Check if the device type is mobile
if (_klOnsite.isMobile()) {
// Set the form ID for nift traffic and mobile device
formId = formIdForNiftTrafficMobile;
} else {
// Set the form ID for nift traffic and desktop device
formId = formIdForNiftTrafficDesktop;
}
} else {
// Check if the device type is mobile
if (_klOnsite.isMobile()) {
// Set the form ID for other traffic and mobile device
formId = formIdForOtherTrafficMobile;
} else {
// Set the form ID for other traffic and desktop device
formId = formIdForOtherTrafficDesktop;
}
}

// Load and show the form with the specified form ID
_klOnsite.push(['openForm', formId]);
}

// Define a function to execute after Klaviyo.js has loaded
function executeAfterKlaviyoLoad() {
// Check if the current URL is not a checkout or order page
if (!isCheckoutOrOrderPage()) {
// Show the form based on the referrer and the device type
showFormBasedOnReferrerAndDevice();

// Add an event listener for klaviyoForms events
window.addEventListener('klaviyoForms', function(event) {
// Track the form activity with some properties
_kmq.push(['track', 'Form ' + event.detail.type, {
'Form ID': event.detail.formId,
'Referrer': document.referrer || ''
}]);
});

// Add an event listener for click events on the document body
document.body.addEventListener('click', function(event) {
// Check if the click target is not inside a klaviyo-form element
if (!event.target.closest('.klaviyo-form')) {
// Close all forms on click outside of them
_klOnsite.push(['closeAllForms']);
}
});

// Define an object to store the display rules for the forms
var displayRules = {
'showOnExitIntent': true, // Show on exit intent
'showAfterDelay': true, // Show after delay of 5 seconds
'delaySeconds': 5,
'showAfterScrollPercent': true, // Show after scroll percent of 50%
'scrollPercent': 50,
'hideAfterSubmission': true, // Hide after submission for 90 days
'hideDays': 90,
'showOnAllDevices': true // Show on all devices
};

// Apply the display rules to all forms on this page
_klOnsite.push(['applyDisplayRules', displayRules]);

// Alternatively, you can apply different display rules to different forms by using their IDs, for example:
//_klOnsite.push(['applyDisplayRules', displayRules, ['form-id-1', 'form-id-2']]);

// Or you can apply different display rules to different forms by using their tags, for example:
//_klOnsite.push(['applyDisplayRulesByTag', displayRules, ['tag-1', 'tag-2']]);

// Or you can apply different display rules to different forms by using their categories, for example:
//_klOnsite.push(['applyDisplayRulesByCategory', displayRules, ['category-1', 'category-2']]);

// For more information about display rules, see https://help.klaviyo.com/hc/en-us/articles/115005082927#display-rules4

}
}

// Execute the function only after Klaviyo.js has loaded
_klOnsiteLoad(executeAfterKlaviyoLoad);

 

Userlevel 7
Badge +60

Hi there @bhas

 

Thanks for your patience! 

 

Yes, you are correct! I was able to touch base with our experts and they confirmed that any code snippets making reference to other code snippets/variables should work inserting into your website via GTM. However, it should be noted that you need to place the custom coded form’s trigger script in the same GTM script as your .js onsite tracking script. GTM should automatically put it the script all pages for you. 

 

Unfortunately, we cannot troubleshoot or support any custom coding. However, you can reach out to our many of partners, or better yet Community Champions, who would be more than happy to help set this up for you! 

 

-Taylor

Userlevel 1
Badge +5

Thanks for the clarification, @Taylor Tarpley .

@Bobi N. , @chelsgrove , @Akers Digital , would love your suggestions on this issue of using custom triggers to load a form.

TL:DR: I created two different forms that will load based on traffic source, and used AI to generate custom trigger code, but this code isn’t working as it should. 

 

Hi @Taylor Tarpley 

When you are loading forms using custom triggers, you have to select the “Only show form based on custom triggers” under the Display Timing section in Targeting and Behavior settings as per this article, correct?

So, I got AI to create this code that will show and hide forms based on traffic source, but also includes standard rules that you would normally set from the “Display according to rules” option, like when can a form show up or which pages it should not. 

I installed it in the theme.liquid file in Shopify just before </head>.

However, none of the forms showed up on testing. 

Could you please run this code-snippet by your engineers to check for any issues?
 

// Define a function to check if the current URL contains /checkouts or /orders
function isCheckoutOrOrderPage() {
// Get the current URL
var currentUrl = window.location.href;
// Convert the current URL to lowercase
currentUrl = currentUrl.toLowerCase();
// Define a regular expression pattern to match /checkouts or /orders
var checkoutOrOrderPattern = /\/(checkouts|orders)\//i;
// Return true if the current URL matches the pattern, false otherwise
return checkoutOrOrderPattern.test(currentUrl);
}

// Define a function to show the form based on the referrer and the device type
function showFormBasedOnReferrerAndDevice() {
// Get the referrer URL or use an empty string as a fallback
var referrer = document.referrer || '';
// Convert the referrer to lowercase
referrer = referrer.toLowerCase();

// Define the form IDs for different traffic types and device types
var formIdForNiftTrafficDesktop = 'your-popup-form-id-for-nift-traffic-desktop';
var formIdForNiftTrafficMobile = 'your-popup-form-id-for-nift-traffic-mobile';
var formIdForOtherTrafficDesktop = 'your-popup-form-id-for-other-traffic-desktop';
var formIdForOtherTrafficMobile = 'your-popup-form-id-for-other-traffic-mobile';

// Define a regular expression pattern to match the referrer URL
var niftPattern = /nift/i;

// Define a variable to store the form ID based on the referrer and the device type
var formId;

// Check if the referrer URL matches the nift pattern
if (referrer.match(niftPattern)) {
// Check if the device type is mobile
if (_klOnsite.isMobile()) {
// Set the form ID for nift traffic and mobile device
formId = formIdForNiftTrafficMobile;
} else {
// Set the form ID for nift traffic and desktop device
formId = formIdForNiftTrafficDesktop;
}
} else {
// Check if the device type is mobile
if (_klOnsite.isMobile()) {
// Set the form ID for other traffic and mobile device
formId = formIdForOtherTrafficMobile;
} else {
// Set the form ID for other traffic and desktop device
formId = formIdForOtherTrafficDesktop;
}
}

// Load and show the form with the specified form ID
_klOnsite.push(['openForm', formId]);
}

// Define a function to execute after Klaviyo.js has loaded
function executeAfterKlaviyoLoad() {
// Check if the current URL is not a checkout or order page
if (!isCheckoutOrOrderPage()) {
// Show the form based on the referrer and the device type
showFormBasedOnReferrerAndDevice();

// Add an event listener for klaviyoForms events
window.addEventListener('klaviyoForms', function(event) {
// Track the form activity with some properties
_kmq.push(['track', 'Form ' + event.detail.type, {
'Form ID': event.detail.formId,
'Referrer': document.referrer || ''
}]);
});

// Add an event listener for click events on the document body
document.body.addEventListener('click', function(event) {
// Check if the click target is not inside a klaviyo-form element
if (!event.target.closest('.klaviyo-form')) {
// Close all forms on click outside of them
_klOnsite.push(['closeAllForms']);
}
});

// Define an object to store the display rules for the forms
var displayRules = {
'showOnExitIntent': true, // Show on exit intent
'showAfterDelay': true, // Show after delay of 5 seconds
'delaySeconds': 5,
'showAfterScrollPercent': true, // Show after scroll percent of 50%
'scrollPercent': 50,
'hideAfterSubmission': true, // Hide after submission for 90 days
'hideDays': 90,
'showOnAllDevices': true // Show on all devices
};

// Apply the display rules to all forms on this page
_klOnsite.push(['applyDisplayRules', displayRules]);

// Alternatively, you can apply different display rules to different forms by using their IDs, for example:
//_klOnsite.push(['applyDisplayRules', displayRules, ['form-id-1', 'form-id-2']]);

// Or you can apply different display rules to different forms by using their tags, for example:
//_klOnsite.push(['applyDisplayRulesByTag', displayRules, ['tag-1', 'tag-2']]);

// Or you can apply different display rules to different forms by using their categories, for example:
//_klOnsite.push(['applyDisplayRulesByCategory', displayRules, ['category-1', 'category-2']]);

// For more information about display rules, see https://help.klaviyo.com/hc/en-us/articles/115005082927#display-rules4

}
}

// Execute the function only after Klaviyo.js has loaded
_klOnsiteLoad(executeAfterKlaviyoLoad);

 

 

 

Reply