Skip to content

Instantly share code, notes, and snippets.

@simple10
Created June 3, 2022 18:16
Show Gist options
  • Save simple10/ad3934bff43a19c0b38aa5bf988ffdae to your computer and use it in GitHub Desktop.
Save simple10/ad3934bff43a19c0b38aa5bf988ffdae to your computer and use it in GitHub Desktop.
Script to listen for embedded mailchimp form submit and fire Facebook tracking on success.
// This is janky due to using setTimeout, but it works.
//
// Supports multiple mailchimp forms embedded on the page.
// Only works if ajax is used which typically requires captch being turned off in mailchimp.
// After a mailchimp form is submitted, the script waits 1 second and looks for a success message
// for the particular form that was submitted. It will retry 10 times before giving up.
//
// Does not support IE11 due to use of forEach unless a polyfill is present.
//
window.addEventListener('DOMContentLoaded', function(event) {
var checkSuccess = function(form, tries) {
if (!tries) tries = 0;
tries++;
if (tries > 10) return;
if (form.querySelector('#mce-success-response').innerHTML.length > 0) {
// Send facebook lead event
// Add other tracking events here as needed
fbq('track', 'Lead');
} else {
setTimeout(function(){checkSuccess(form, tries)}, 1000)
}
}
// Get all mailchimp embedded forms and attach event listeners
document.querySelectorAll('#mc-embedded-subscribe-form').forEach(function(form){
form.addEventListener('submit', function(event){checkSuccess(event.target)});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment