Last active
April 6, 2018 16:35
-
-
Save hutch78/d1e5033b498a6d6165860cc67f42d244 to your computer and use it in GitHub Desktop.
PCOMM - Open links and files in new tab, fire analytics event
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$(document).ready(function($){ | |
var anchorElements = $('a'); | |
var eventDefaults = { | |
category: 'Links', | |
value: 0 | |
} | |
var fileTypes = new RegExp(/\.(docx*|xlsx*|pptx*|zip|pdf)$/i); | |
var mailtoPattern = new RegExp('/mailto:/'); | |
anchorElements.each(function(i, el) { | |
// console.log('testing....', el); | |
var a = new RegExp('/' + window.location.host + '/'); | |
var hasOpenTabClass = el.classList.contains('open-in-new-tab'); | |
var action = ''; | |
var isMailtoLink = this.href.indexOf('mailto:') == 0; | |
// if target URL contains the string ".pdf" | |
var isPDF = this.href.indexOf('.pdf') != -1; | |
if (fileTypes.test(this.href)) { | |
action = 'Download'; | |
} else { | |
action = 'External Link' | |
} | |
if((!a.test(this.href) || hasOpenTabClass || fileTypes.test(this.href)) && !isMailtoLink) { | |
$(this).click(function(event) { | |
event.preventDefault(); | |
var thisEvent = { | |
label: this.href, | |
action: action | |
} | |
var externalEventData = $.extend(thisEvent, eventDefaults); // merge new event data with default data object | |
pcommAnalytics.trackAnalyticsEvent(externalEventData); // use pcomm-analaytics to manually send GA event | |
event.stopPropagation(); | |
window.open(this.href, '_blank'); | |
return false; | |
}); | |
} | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
this has some bugs.