JSFiddle - React, Tailwind, and code Playground
HTML
<a target="_blank" href="#">
<img class="pin-image" article-url="http://example.com"...
JavaScript
function pinterestShareFormatter(imgSelector) {
var imgs = document.querySelectorAll(imgSelector),
baseUrl = '//www.pinterest.com/pin/create/button/?';
[].forEach.call(imgs, function(img) {
var imgSrc = img.getAttribute('src'),
articleUrl = img.getAttribute('article-url') ? img.getAttribute('article-url') : window.location.href, // check if there is article url attribute and if not assign the current page url.
parentAnchorEl = img.parentNode;
// check if parent element is <a>
if(parentAnchorEl.tagName === 'A') {
// format the url params
var params = {
url: articleUrl,
media: imgSrc
},
paramsString = Object.keys(params).map(function(key){return key + '=' + encodeURIComponent(params[key]);}).join('&');
// update the anchor with formatted url
parentAnchorEl.setAttribute('href', baseUrl + paramsString);
}
});
}
pinterestShareFormatter('.pin-image');