Subrata
Subrata

Reputation: 2284

How to give image url to Pinit button?

I am trying to add the Pinit button to my website. The problem is that, the Pinit button requires the image url, but in my case the images are generated dynamically. So how do I add the Pinit button such that it Pins the the visible image of the page.

Something like this example will do great.

Upvotes: 1

Views: 338

Answers (2)

Yusaf Khaliq
Yusaf Khaliq

Reputation: 3393

http://jsfiddle.net/t4KHR/

run the below code once you have dynamically appended the images set the parent variable as the ID parent of the images you want sharing

var url = document.location.href;
var parent = document.getElementById("imgholder");
var img = parent.getElementsByTagName("img");
for (i = 0; i < img.length; i++) {
    var newpin = document.createElement("a");
    newpin.href = 'http://pinterest.com/pin/create/button/?url=' + encodeURIComponent(url) + '&media=' + encodeURIComponent(img[i].src);
    newpin.className = "pin-it-button";
    img[i].parentNode.insertBefore(newpin, img[i].nextSibling)
    if (i == img.length - 1) {
        var s = document.createElement("script");
        s.type = "text/javascript";
        s.src = "//assets.pinterest.com/js/pinit.js";
        document.getElementsByTagName("body")[0].appendChild(s);
    }

}

Upvotes: 2

Subrata
Subrata

Reputation: 2284

<a class="pin-it-button" href="javascript:void((function()%7Bvar%20e=document.createElement('script');e.setAttribute('type','text/javascript');e.setAttribute('charset','UTF-8');e.setAttribute('src','http://assets.pinterest.com/js/pinmarklet.js?r='+Math.random()*99999999);document.body.appendChild(e)%7D)());">

<img border="0" src="//assets.pinterest.com/images/PinExt.png" title="Pin It" />

</a>

The code snippet given above solved my problem. What it does is rather than hardcoding the URL's to the code links, it uses javascript to fetch the current url and shows the images of the current pages to be Pinned. And don't forget to include the following script in your header or footer

<script type="text/javascript" src="//assets.pinterest.com/js/pinit.js"></script>

Upvotes: 1

Related Questions