Created
November 2, 2019 23:27
-
-
Save nandorojo/1fbe463788cbd48317bc0a4fcdde42c5 to your computer and use it in GitHub Desktop.
Segment.io Analytics.js usage on Webflow
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// STEP 0: | |
// add the segment JS web snippet with your custom segment key to your header on webflow. this is found at your webflow project's dashboard -> custom code -> header. | |
// STEP 1: | |
// in the web flow editor, click any element you want to track when clicked, go to its settings, and add custom attributes that follow this pattern: | |
/* | |
~required~ you must add a data-analytics attribute | |
data-analytics="YOUR_EVENT_NAME_HERE" | |
optional: you can add multiple data-property-<name> properties | |
data-property-color="red" | |
data-property-from="nav" | |
*/ | |
// HTML will look like this: <a data-analytics="navigate_home" data-property-from="nav" data-property-from="nav" /> | |
// using the script below, this will send this to segment: | |
// analytics.track('navigate_home', { from: 'nav', mood: 'happy' }) | |
// STEP 2: | |
// paste the code below in your footer code, found at your project's dashboard -> custom code | |
// important: make sure to wrap the code below in a <script></script> | |
// like this: <script>$(document)....</script> | |
$(document).ready(function() { | |
// capture a click on any element that has | |
$('[data-analytics]').on('click', function(e) { | |
var properties | |
var event = $(this).attr('data-analytics') | |
// for each attribute on the element we clicked... | |
$.each(this.attributes, function(_, attribute) { | |
// if this attribute corresponds to a property | |
if (attribute.name.startsWith('data-property-')) { | |
// if this is the first property, make sure properties is a dictionary and not undefined | |
if (!properties) properties = {} | |
// we get this property name. for instance, <a data-property-color="red" /> would mean var property = color | |
var property = attribute.name.split('data-property-')[1] | |
// following the previous example, attribute.value = red, so we set properties['color'] = red | |
properties[property] = attribute.value | |
} | |
}) | |
console.log('segment:', { event: event, properties: properties }) | |
analytics.track(event, properties) | |
}) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment