Forked from hutch78/open-links-in-new-tab-with-analytics.js
Last active
April 6, 2018 16:36
-
-
Save philpalmieri/fd5d86def8329b38916372714ccf4928 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' | |
} | |
//Verify a anchor has an href, so we dont get a million open tabs on load | |
if((this.href && ( !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