Skip to content

Instantly share code, notes, and snippets.

@jhubert
Last active November 5, 2018 04:19
Show Gist options
  • Save jhubert/74b540fb2a66953fe2564f96ac36acf9 to your computer and use it in GitHub Desktop.
Save jhubert/74b540fb2a66953fe2564f96ac36acf9 to your computer and use it in GitHub Desktop.
Capture the UTM values from a querystring and store them in a long lived document cookie.
// Append UTM values to any form on the page
(function () {
function getUTMCookies() {
var cookies = {}, pairs = document.cookie.split(";"), i, pair, key;
for (i = 0; i < pairs.length; i++) {
pair = pairs[i].split("=");
key = (pair[0] + '').trim();
if (key.indexOf('utm') > -1) {
cookies[key] = unescape(pair[1]);
}
}
return cookies;
}
function appendUtmToForm() {
var fields = [];
$.each(getUTMCookies(), function (index, value) {
fields.push('<input type="hidden" name="' + index + '" value="' + value + '" />');
});
$('form').append(fields);
}
// Grab the cookie value and set the form field values
appendUtmToForm();
}());
(function () {
var query_string, pieces, hash, key, i, value, exp_date;
function setYearLongCookie(cname, cvalue) {
var expires = "expires=" + exp_date.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
query_string = window.location.search.substr(1);
if (!query_string) {
return;
}
exp_date = new Date();
exp_date.setTime(exp_date.getTime() + (365 * 24 * 60 * 60 * 1000));
pieces = query_string.split('&');
for (i = 0; i < pieces.length; i++) {
hash = pieces[i].split('=');
key = hash[0].toLowerCase();
value = hash[1];
if (key.indexOf('utm') > -1 && value) {
setYearLongCookie(key, value);
}
}
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment