shareon-pulsanti-condivisio.../src/shareon.js

74 lines
2.3 KiB
JavaScript
Raw Normal View History

2020-07-31 18:18:17 +02:00
// eslint-disable-next-line import/no-unresolved
import urlBuilderMap from 'consts:urlBuilderMap';
2020-03-25 21:47:00 +01:00
2020-07-31 18:18:17 +02:00
const initializeShareon = () => {
2020-03-25 21:47:00 +01:00
const shareonContainers = document.getElementsByClassName('shareon');
// iterate over <div class="shareon">
2020-03-25 21:47:00 +01:00
for (let i = 0; i < shareonContainers.length; i += 1) {
2020-07-31 18:18:17 +02:00
/** @type Element */
const container = shareonContainers[i];
2020-03-25 21:47:00 +01:00
// iterate over children of <div class="shareon">
2020-03-25 21:47:00 +01:00
for (let j = 0; j < container.children.length; j += 1) {
2020-07-31 18:18:17 +02:00
/** @type Element */
const child = container.children[j];
2020-03-25 21:47:00 +01:00
if (child) {
const classListLength = child.classList.length;
2020-03-25 21:47:00 +01:00
// iterate over classes of the child element
for (let k = 0; k < classListLength; k += 1) {
const cls = child.classList.item(k);
// if it's one of the networks
2020-07-31 18:16:59 +02:00
if (Object.prototype.hasOwnProperty.call(urlBuilderMap, cls)) {
const preset = {
url: encodeURIComponent(
child.dataset.url
2020-07-31 18:18:17 +02:00
|| container.dataset.url
|| window.location.href,
),
title: encodeURIComponent(
child.dataset.title
2020-07-31 18:18:17 +02:00
|| container.dataset.title
|| document.title,
),
media: encodeURIComponent(
child.dataset.media
2020-07-31 18:18:17 +02:00
|| container.dataset.media
|| '',
),
text: encodeURIComponent(
child.dataset.text
2020-07-31 18:18:17 +02:00
|| container.dataset.text
|| '',
),
via: encodeURIComponent(
child.dataset.via
2020-07-31 18:18:17 +02:00
|| container.dataset.via
|| '',
),
};
2020-07-31 18:16:59 +02:00
const url = urlBuilderMap[cls](preset);
if (child.tagName.toLowerCase() === 'a') {
child.setAttribute('href', url);
child.setAttribute('rel', 'noopener noreferrer');
child.setAttribute('target', '_blank');
} else {
child.addEventListener('click', () => {
window.open(url, '_blank', 'noopener,noreferrer').opener = null;
});
}
break; // once a network is detected we don't want to check further
}
}
}
2020-03-25 21:47:00 +01:00
}
}
};
export default initializeShareon;