Skip to content

Instantly share code, notes, and snippets.

@kanakiyajay
Created October 18, 2014 14:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kanakiyajay/505d862d107226d5957d to your computer and use it in GitHub Desktop.
Save kanakiyajay/505d862d107226d5957d to your computer and use it in GitHub Desktop.
Add Utm params to each and every link of your website.
(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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment