Skip to content

Instantly share code, notes, and snippets.

@dillansimmons
Created October 25, 2016 19:29
Show Gist options
  • Select an option

  • Save dillansimmons/ed5694d3fc472eb3b31b8b17a4004c93 to your computer and use it in GitHub Desktop.

Select an option

Save dillansimmons/ed5694d3fc472eb3b31b8b17a4004c93 to your computer and use it in GitHub Desktop.

Revisions

  1. dillansimmons created this gist Oct 25, 2016.
    36 changes: 36 additions & 0 deletions firstTouchUTMCookie.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,36 @@
    // 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);