Skip to content

Instantly share code, notes, and snippets.

@rafaelfaria
Last active February 13, 2017 22:37
Show Gist options
  • Save rafaelfaria/2a99e9f8294454f3acdd9c287288ffc3 to your computer and use it in GitHub Desktop.
Save rafaelfaria/2a99e9f8294454f3acdd9c287288ffc3 to your computer and use it in GitHub Desktop.
const SELECTOR = '.share-tools'
class SocialTools {
constructor() {
}
/**
* Get an array of instances for this Module.
* @return {Object[]}
*/
get instances() {
return [...document.querySelectorAll(SELECTOR)];
}
addClickEvents() {
this.instances.forEach((instance) => {
let links = [...instance.querySelectorAll('.share-tools-btn')];
links.forEach((link) => link.addEventListener('click', this.onButtonClick.bind(this)));
});
}
onButtonClick(e) {
e.preventDefault();
const element = e.currentTarget,
href = element.getAttribute('href') || '',
socialUrl = element.getAttribute('data-social-url') || '',
currentUrl = location.href,
title = document.querySelector('title').innerHTML,
description = document.querySelector('description').innerHTML,
url;
// If there is no url assigned then get the information from the meta tags and build it
if (href === '' || href === '#') {
url = this.buildSocialUrl(socialUrl, title, currentUrl, description);
} else {
url = this.buildSocialUrl(socialUrl, title, href, description);
}
let newWindow = window.open(url, '_blank');
newWindow.location;
}
buildSocialUrl(socialUrl, title, url, description) {
return socialUrl
.replace(/{URL}/gi, url)
.replace(/{DESCRIPTION}/gi, description)
.replace(/{TITLE}/gi, title);
}
init() {
this.addClickEvents();
}
}
if (typeof exports === 'object') {
exports.SocialTools = SocialTools;
} else {
window.GoogleAnalyticsTracking = new SocialTools();
window.GoogleAnalyticsTracking.init();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment