Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

adding facebook like buttons dynamically after loading

I am attempting to add like buttons to a page using the standard like button code as proided in the fb documentation:

https://developers.facebook.com/docs/plugins/like-button/

This is causing extremely slow loading due to the number of buttons I would like to add.

To get round this I was hoping to load the buttons as needed using jquery, but if I add the button code this way, they are appended to the the correct location (visible in the developer tools elements window) but the buttons do not appear.

Is there anyway to add these buttons dynamically? I am guessing it is not working because the buttons can't be added after initiation but I have no idea how to get around this.

I included the required code inside the body tag

<div id="fb-root"></div>
<script type="text/javascript">
    (function(d, s, id) {
        var js, fjs = d.getElementsByTagName(s)[0];

        if (d.getElementById(id)){
            return;
        }

        js = d.createElement(s); js.id = id;
        js.src = "//connect.facebook.net/en_GB/all.js#xfbml=1&appId=************";
        fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
 </script>

The fb-like code I am using is the one generated by the documentation:

<div class="fb-like" data-href="https://developers.facebook.com/docs/plugins/" data-layout="button_count" data-action="recommend" data-show-faces="false" data-share="true"></div>

I have tried adding a button this way:

   $(".myitem").append('<div class="fb-like" data-href="https://developers.facebook.com/docs/plugins/" data-layout="button_count" data-action="recommend" data-show-faces="false" data-share="true"></div>');                   

UPDATE:

I have tried firing FB.XFBML.parse(); after appending the new buttons, but this refreshes all of the buttons on the page not just the newly appended ones.

like image 342
Finglish Avatar asked Nov 17 '13 19:11

Finglish


People also ask

How do I enable like button?

Go to Settings › General, then click the Share tab. Enable the Facebook Like/Recommend button setting by clicking the “thumb up” Like icon. Then click the settings (...) icon in the upper left of the button.

How does the Facebook like button work?

When a user clicks the like button, the content appears in the News Feeds of that user's friends. The button also displays the number of users who liked each piece of content, and may show a full or partial list of those users.


1 Answers

To force the refresh / rendering of the Like button, you can use FB.XFBML.parse(); which go through the whole DOM document.

If you only want to go through a part of the document, you can pass a DOM object (which is for example a container element with 1 button).

FB.XFBML.parse(document.getElementById('containerX'));
like image 90
Mike Vranckx Avatar answered Nov 09 '22 01:11

Mike Vranckx