Skip to content

Instantly share code, notes, and snippets.

@dillansimmons
Created October 25, 2016 19:29
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dillansimmons/ed5694d3fc472eb3b31b8b17a4004c93 to your computer and use it in GitHub Desktop.
Save dillansimmons/ed5694d3fc472eb3b31b8b17a4004c93 to your computer and use it in GitHub Desktop.
Store first touch utm in cookie and input into hidden field (Cookie.js, JQuery)
// Initiate JQUERY
// Initiate cookie.js : https://github.com/js-cookie/js-cookie
// Parse the URL
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
// Give the URL parameters variable names
var source = getParameterByName('utm_source');
var medium = getParameterByName('utm_medium');
var campaign = getParameterByName('utm_campaign');
var content = getParameterByName('utm_content');
var term = getParameterByName('utm_term');
// Set utm function: assumes all hidden fields follow this format : <input name="utm_term" type="hidden">
var set_utm = function setutm(utm_param, utm_val){
if (Cookies.get(utm_param+'y') != undefined) {
$('input[name="utm_'+utm_param+'"]').val('');
//console.log('Reset code for cookie time');
$('input[name="utm_'+utm_param+'"]').val(Cookies.get(utm_param+'y'));
//console.log('Set input to ' + Cookies.get(utm_param+'y'));
} else {
//console.log('Using current code / no code set');
if (utm_val != "" ) {
//console.log('Set the cookie');
Cookies.set(utm_param+'y', utm_val, {path: '/'});
};
};
}
// Do the function for each UTM
set_utm('source', source);
set_utm('medium', medium);
set_utm('campaign', campaign);
set_utm('content', content);
set_utm('term', term);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment