Skip to content

Instantly share code, notes, and snippets.

@jonkiddy
Created March 29, 2017 14:22
Show Gist options
  • Save jonkiddy/0394614af44792a44ab0a72afbc355ed to your computer and use it in GitHub Desktop.
Save jonkiddy/0394614af44792a44ab0a72afbc355ed to your computer and use it in GitHub Desktop.

Revisions

  1. jonkiddy created this gist Mar 29, 2017.
    45 changes: 45 additions & 0 deletions js_utm_codes.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,45 @@
    (function addUtmParams(source, medium, campaign) {
    $("a").each(function () {
    var $this = $(this);
    var linkHref = $this.attr("href");
    if (linkHref.indexOf(window.location.hostname) < 0) {
    var updateLink = updateQueryString({
    utm_source: source,
    utm_medium: medium,
    utm_campaign: campaign
    }, linkHref);
    $this.attr("href", updateLink);
    }
    });
    })("jquer.in", "website", "content-curation");
    // The thee configurable options ( utm_source, utm_medium, utm_campaign)
    // The following functions is inspired from http://stackoverflow.com/questions/5999118/add-or-update-query-string-parameter

    function updateQueryString(params, url) {

    if (!url) url = window.location.href;
    for (var key in params) {
    if (params.hasOwnProperty(key)) {
    var value = params[key];
    var re = new RegExp("([?&])" + key + "=.*?(&|#|$)(.*)", "gi");
    if (re.test(url)) {
    if (typeof value !== 'undefined' && value !== null)
    return url.replace(re, '$1' + key + "=" + value + '$2$3');
    else {
    var hash = url.split('#');
    url = hash[0].replace(re, '$1$3').replace(/(&|\?)$/, '');
    if (typeof hash[1] !== 'undefined' && hash[1] !== null)
    url += '#' + hash[1];
    }
    }
    else if (typeof value !== 'undefined' && value !== null) {
    var separator = url.indexOf('?') !== -1 ? '&' : '?',
    hash = url.split('#');
    url = hash[0] + separator + key + '=' + value;
    if (typeof hash[1] !== 'undefined' && hash[1] !== null)
    url += '#' + hash[1];
    }
    }
    }
    return url;
    }