Search code examples
javascriptjquerysocial-networkinggoogle-plus-one

Set Google +1 button url with javascript


I am building an image gallery that is slider based and loads new images via javascript and have a requirement to set the Google +1 button's URL via javascript so +1 can be set on each image.

I also need to reload the +1 button based on each image (the url will have a querystring parameter containing the image id to make it unique). Is this possible?


Solution

  • <!-- Place this tag where you want the +1 button to render -->
    <div class="g-plusone" data-annotation="inline" data-href="#"></div>
    
    <!-- Place this render call where appropriate -->
    <script type="text/javascript">
    (function() {
       var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
       po.src = 'https://apis.google.com/js/plusone.js';
       var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
    })();
    

    You can use the following code to alter the gplus href attribute using jQuery. Make sure to include jquery library first and then use the code below:

    <script type="text/javascript">
       jQuery(".your-button").click(function(){
           jQuery(".g-plusone").attr("data-href","Your-Value-Goes-Here");
       });
    </script>