Search code examples
jqueryhrefgoogle-plus

Change the href of the google +1 button using jquery


how can I change the href attribute of my google +1 button via some jQuery

The button initially loads with an empty href.

here is what I have tried so far

$(document).ready(function () {
    var qrCode = 'A12345';
    var shareLink = "http://<?php echo $_SERVER['HTTP_HOST'];?>/show.php?qrCode="+qrCode;
    $("#shareLink").attr("href", shareLink);
});

<g:plusone size='medium' id='shareLink' annotation='none' href='' callback='countGoogleShares'></g:plusone>

Solution

  • I finally got it to work the way I wanted it to. I restructured the code a bit to get it to work. Instead of trying to change out the href attribute on document.ready, I ended up creating an empty div to be the container for the google plus button and writing the button with the correct href via .html()

    //load the google plus javascript api
    <script type="text/javascript" src="https://apis.google.com/js/plusone.js">
        {"parsetags": "explicit"}
    </script>
    
    //create an empty div to be the target of the google plus button
    <div id="plusContent"></div>
    
    <script>
        //get the qrcode to append to the url (ajax call in real life)
        var qrCode = 'A12345';
    
        //build the google plus object text string
        var googleShareLink = "<g:plusone size='medium' id='shareLink' class='shareLink'  annotation='none' href='http://<?php echo $_SERVER['HTTP_HOST'];?>/show.php?qrCode="+qrCode+"' callback='countGoogleShares'></g:plusone>";
    
        //write the google plus object to the target div
        $("#plusContent").html(googleShareLink);
    
        //render the +1 buttons in the target location
        gapi.plusone.go("plusContent");
    </script>