Contact Us
  • Tutorial: How to Add a Facebook Share Button to your Website Pages

    If you’re not on the HyperArts Blog, CLICK HERE.

    In a previous post, Bill Dailey provided detailed instruction on how to add a “classic” Facebook Share Button to your custom iFrame tabs, and replicate the Share Button previously done with the <fb:share-button> FBML tag.

    In this post, I show you how to add the same classic Share Button to your own Web pages, so that people can share your website content on Facebook. (View and test this example.)

    STEP 1: Get a Facebook App ID for the domain the Share Button will live on.

    To add the Share Button to your website, Facebook requires that your domain have an “App ID” or “appId” which it says is “a unique identifier for your site that ensures that we have the right level of security in place between the user and your website.”

    Read my tutorial on getting a Facebook App ID for your website.

    STEP 2: Add the Facebook JavaScript SDK to your Web page.

    The code that Facebook provides for your Web page, to load and initialize the JavaScript SDK, should be added within the <body> ... </body> tags of your .html, .php or .asp file.

    Use the Asynchronous JavaScript SDK Code

    On its JavaScript SDK page, Facebook provides two ways to import the JavaScript SDK: 1) Synchronously (loads in the order it appears in your code) or 2) “Asyncronously” where other elements on your page will load even if the SDK for some reason doesn’t load. Facebook recommends the Asynchronous method, and you’ll definitely want to use the Asynchronous method or your Share Button won’t work in Internet Explorer.

    Here is the Asynchronous code to add to your Web page:

    <div id="fb-root"></div>
    <script>
    window.fbAsyncInit = function() {
    FB.init({appId: 'YOUR APP ID', status: true, cookie: true,
    xfbml: true});
    };
    (function() {
    var e = document.createElement('script'); e.async = true;
    e.src = document.location.protocol +
    '//connect.facebook.net/en_US/all.js';
    document.getElementById('fb-root').appendChild(e);
    }());
    </script>

    NOTE: Make sure you replace ‘YOUR APP ID’ with your actual App ID for your website. You can always find it on the Facebook Application Page. (When logged in to Facebook, you’ll see all applications you’ve created under your personal profile.)

    STEP 3: Add code to load the jQuery library on your Web page

    Next, you need your Web page to load jQuery, a JavaScript library that simplifies many JavaScript-related tasks.

    We like using the jQuery library from Google as it loads quickly and many people will already have it cached in their browser history.

    Just add the following code to your Web page:

    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js" type="text/javascript"></script>

    STEP 4: Add some jQuery and fb.ui code to display the Share dialog box

    Now that you have loaded the Facebook JavaScript SDK and jQuery, we can define the Share Button dialog using some jQuery and the Facebook function fb.ui. Insert the following code on your Web page:

    <script type="text/javascript">
    $(document).ready(function(){
    $('#share_button').click(function(e){
    e.preventDefault();
    FB.ui(
    {
    method: 'feed',
    name: 'This is the content of the "name" field.',
    link: ' http://www.hyperarts.com/',
    picture: 'http://www.hyperarts.com/external-xfbml/share-image.gif',
    caption: 'This is the content of the "caption" field.',
    description: 'This is the content of the "description" field, below the caption.',
    message: ''
    });
    });
    });
    </script>

    This code tells jQuery to attach a Share dialog to the DIV in your code with the ID of “share_button”. You can insert multiple share buttons on a page by repeating this code, making sure you use a unique ID for each (eg #share_button1, #share_button2).

    This code will create this popup dialog:
    Facebook Share Dialog

    You can customize the text and image in the Share dialog and post by changing these values:

    • Name: The text that appears on the first line of the Share dialog, below the personalized message box. It is hyperlinked to the URL you set for the “link” value. Maximum displayed characters: 99;
    • Link: The URL you want to share when users click the Name field; IMPORTANT: The link URL has to be under the same domain as the page with the Share Button. For example, our demo of this Share Button is hosted at http://http://www.hyperarts.com/external-xfbml/share-button.html and the link it shares is http://www.hyperarts.com.

      If your Share URL is on a domain/website other than the one where the button is, you’ll get an error message similar to this:

    • Picture: The URL of the image you want to display with the post on your Wall/News Feed. In the above example I used a 90×90 pixel image, but Facebook seems to allow some flexibility around this image size. Make sure you check how your image displays in your News Feed!
    • Caption: This text displays under the Name/Link. Maximum displayed characters: 100;
    • Description: This text displays under the Caption. Maximum displayed characters: 270, followed by a “See more” link to show the rest;
    • Message: This field allowed you to pre-populate the personalized message box at the top of the Share dialog. However, Facebook would prefer that you don’t pre-populate the message field as they want the user to enter a personalized message and, as Alison Gianotto at Snipe.Net pointed out, the “message” field has been deprecated and is now ignored. So just leave it blank.

    The small “H” logo and “via HyperArts” — just below the green “heart” image — represent the small icon you set for the Facebook application you created to obtain your App ID; and “HyperArts” is the name of that Facebook application. (See my tutorial on creating a Facebook App to get an App ID for your website.)

    STEP 5: Add a text or image link that triggers the Share dialog

    You can launch the the Share dialog using either linked text or an image. We wanted to create the “classic” Share Button to which users have become very accustomed, so we used an image, creating a graphic that replicates the classic “Share” button:

    Just insert the link/image in your index file and add the ID “share_button.”

    <img src = "share_button.png" id = "share_button">

    When a user clicks on that button, it will pop up the Share dialog box.

    Once the user fills in their message and clicks the Publish button, the post will appear on their Wall and may appear in their friends’ News Feeds (depending on their settings).

    Facebook Share Button Wall Post

    Step 6: Control the Cursor Style with CSS

    Control Share Button Cursor with CSSTo add a custom cursor to the Share Button with CSS:

     

    • Add this style to your stylesheet:

      img#share_button {cursor: pointer;}

    • Or inline the style on the page:

      <style type=”text/css”> img#share_button {cursor: pointer;} </style>

    View a live example of our Share Button.

    You can see an example of this code in action here.

    Download the Sample Code

    Download our Facebook Share Button code for our Share Button Example to get you started. Make sure you update the APP ID, text, and images as needed!

    Comments

    1. Refresh my memory … does the share button act like the “like” button (except it makes more sense because you’re really sharing it – but Facebook changed it for some odd reason)?

      If so, and I understand correctly, you can implement a Like button using Facebook’s social plugins – but – this tutorial is a useful workaround so that we can have a button that actually makes sense to our audience and is more likely to be used.

      • Jodi, With the Like Button, you can only control the URL that is liked, and then the accompanying image and text are auto-generated by either what exists of Facebook (the Profile Picture & About Box text if the Liked URL is a fan page), or by meta tags on a Web page (the title tag and image defined by “image_src” or <meta property=”og:image” content=”URL OF IMAGE” />).

        And if the user doesn’t add a personalized message, then what shows up on their Wall may just be a text link (eg “Jodi likes Some Company”).

        However, with the Share Button, you can control those above parameters independent of the URL being shared. And it will appear on your Wall/News Feed with the image and text you define in the code.

    2. I love this! How can I add this to a WordPress site? Is there a plug-in to make it easy, or do I need to paste the code in.If I need to paste the code, exactly where should I put it?

      Thanks!

      • There may be a WordPress plugin for this. You’ll have to search. Otherwise you’d have to edit your header.php file to add the appropriate code. This would involve some PHP as you’d probably want the Share Button on each post to be for that specific post.

        I did do an article sometime back about how to manually add the Facebook Social Plugins to a WordPress blog, so you could check that out.

        Of course, you can only edit your WordPress files if your blog is self-hosted.

    3. Hi Tim. My Share button seems to produce an error in Internet Explorer. Rarely does it happen to me on my mac on any of my browsers.

      The index page I am hosting everything is on is here:
      http://www.myrosscareer.com/_assets/facebook/rossmedical/free_tshirt_tab/index.php

      I also have it iframed on this facebook page tab: http://www.facebook.com/RossMedical?sk=app_190322544333196

      Internet explorer seems to be the browser that is difficult. I am no coding/java expert… Any advice?

      CODE IS BELOW…

      [CODE DELETED]

      • Jeff, Please read my post a bit closer. You want to use the Asynchronous method of loading the JavaScript SDK. If you don’t, IE does throw errors.

    4. Ronald Steiner says:

      Thanks a lot for this awesome tutorial.
      - maybe you got a hint for me for further study.
      I want to combine the “share” and “like” button. – When a user clicks on it he automatically likes the page and shares it on his facebook wall. – without typing in any specific message.
      Is there a way to achieve this?
      greetings
      Ronald

      • Ronald, You can just use the Like button on the Facebook Social Plugins page. When the user Likes your page and adds a message it posts to their Wall. Without the message, however, it usually just does a sentence on the Wall. I don’t know how to do what you asking. Sorry!

    5. Really awesome work..but i need to give user option to choose thumbnail from more than 2 option..
      What should i do to make it work.??
      Please guide me.

    6. Thanx for looking at my comment..i really appreciate it.
      well its alwys be a programmer fight so i will find way and lets u knw once i done it.
      so u can help others who wants tackle same problem.

      Thanx u so much

    7. Hi, i developed a facebook app with silverlight and i embed it to facebook but i have a strange problem.
      My facebook app blocks all the page i m sending the link if you want you can see it ;http://www.facebook.com/Co2ncerned?sk=app_134191419994488
      could you please help me ,what is the mistake ?
      Thank you

    8. Thanks for this. Is there any way to easily use the sharer.php style, so that the sharing user can select to share on their wall, send as a message, share on someone else’s wall, etc, without having to re-create the FB box in jQuery? Since this isn’t a standard share, just a feed message, it doesn’t provide those options.

    9. Hey there, this seems to be a very useful code and is exactly what I need. The only problem is that I can’t get it to work. I downloaded the files and updated the APP id but I can’t get the pop up to work. Any thoughts?

      [CODE REMOVED, for brevity]

      • I’m pretty sure the problem is that the domain under which you put the Share Button has to match the domain URL you’re sharing with the button.

        So if you put the Share Button on a page under mydomain.com, then the URL for the “link” value in the script has to be mydomain.com/page-with-share-button.html

        I’ll update this post to make that more clear.

        Cheers!

        • hi, i downloaded the code too, and updated only app ID, leaving the rest of the code intact. it does not seem to work. any idea?

    10. hi, sorry, it worked, how do you set the 90x90px image to something else?

    11. Hi there,

      If you use the Like button on your website to link to your Facebook Fan Page, does the Facebook Fan Page automatically update the number of its fans? For example, if my Facebook Fan Page currently has 10 fans and then I launch a Like button on my website which gets 10 additional likes, if I go to my Fan Page, will it show that I have 20 fans?

      Thanks!

    12. hi, if i have 5 pages and i wanna include the share button on every page, can i just use the same code? or do i have to use unique identifier (e.g. ID for the share button)?

      thanks

    13. Thank you so very much. I have spent over 20 hours trying to use the fb developers way of getting the sharer to work. Using meta tags and such. With your tutorial I was able to get it to work on the 1st try. You are a blessing…thank YOU!!!

    14. Hi Tim. Is there a way of getting the parent page to redirect to a thank you page after the share?

    15. Hey Tim, deadly post! I’m not sure but Fb may have changed something here because my pre populated message isn’t showing up in the text field and neither is it on your example. Do you know what’s up with this? Cheers,

    16. john – Facebook announced a little while back that the prepopulated messages would be deprecated. I think they felt it was being abused and should be for the user to fill in.

      • Hey, Thanks Snipe! That makes total sense. Would you happen to have a URL where Facebook announced this deprecation? Cheers. Tim

        • Argh – I know I have it somewhere. I *think* it was discussed more in depth in the private PDC group, but I’ll see if I can dig it up and point you to a url. I do remember thinking that it was interesting that they didn’t make a bigger deal out of it. I personally rarely used that field, so it didn’t impact me much. Lemme see if I can dig it up for you.

        • Found it! http://developers.facebook.com/blog/post/510/

          “Breaking Change: “message” parameter ignored in Feed Dialog

          On July 12, we are ignoring the message parameter in Feed Dialogs. This eliminates the ability to pre-fill stream stories (prohibited by Policy IV.2). This change encourages users to share authentic and relevant content with their friends. ”

          Hope that helps!

    17. Thanks for the great post Tim,
      A couple of queries for you; is it possible to display the share button image as a hyperlink, i.e. the cursor will change to a hand when moved over the button? Just thinking in terms of accessibility. Also, I can’t get the image to display in news feed – does it have to be in a specific file format?Cheers,Jack

    18. Thanks for the great post Tim,
      A couple of queries for you; is it possible to display the share button image as a hyperlink, i.e. the cursor will change to a hand when moved over the button? Just thinking in terms of accessibility. Also, I can’t get the image to display in news feed – does it have to be in a specific file format?Cheers,Jack

    19. T_parsnick3 says:

      Tim, I tried your example at http://www.hyperarts.com/external-xfbml/share-button.htmlIt publishes to my wall and my newsfeed, but it does not appear in my friends newsfeed.The old share functionality used to also publish in my friends newsfeed. Do you know how to make this new share method using FB.ui and the feed method also publish to my friends newsfeed?  By the way, the new Facebook like button does publish comments to my friends newsfeed.   (sorry for posting this twice….the first post was a reply and got buried in an old thread.  So I posted again.)

      • Not everything you share will show up in your friends’ news feeds. It depends on a number of factors — Facebook was calling this algorithm “EdgeRank” — like how frequently friends “liked” or commented on your updates, or shared them.

        Remember, you’re competing with all the users’ other friends, as well as every Facebook page that they’ve ‘liked’.

        The 3 factors that Facebook uses are:

        Affinity — The number of times two people (or a person and a page) have interacted; 
        Recency — The time since the content was posted;
         
        Weight — the number of times users have interacted (commented, liked) with the content.

        Here’s a very good article on the subject.

      • Not everything you share will show up in your friends’ news feeds. It depends on a number of factors — Facebook was calling this algorithm “EdgeRank” — like how frequently friends “liked” or commented on your updates, or shared them.

        Remember, you’re competing with all the users’ other friends, as well as every Facebook page that they’ve ‘liked’.

        The 3 factors that Facebook uses are:

        Affinity — The number of times two people (or a person and a page) have interacted; 
        Recency — The time since the content was posted;
         
        Weight — the number of times users have interacted (commented, liked) with the content.

        Here’s a very good article on the subject.

    20. Since many days I’d been trying to include facebook share button  in my web page but was not being able to do. Finally, got to learn it. Excellent tutorial. Thank you for providing links to all that we needed in doing the same,viz. getting an App Id, etc.

    21. Anonymous says:

      Hi All,
      my app of this Share Button is hosted at http://localhost:8080/facebkInfo/share/facBk and the link it shares is http://localhost:8080/facebkInfo/.  facebkinfo is my  grails app.In that i create facBk.gsp page. Bt i m getting this error plz help me for solving this issue.

    22. Anonymous says:

      Hi All,
      My appliaction  of this Share Button is hosted at http://localhost:8080/facebkInfo/share/facBk and then the URL for the “link” value in the script has to be http://localhost:8080/facebkInfo.   facebkinfo is my grails application And facbk is my gsp page.I m getting error like specific url is nt owned by the application..plsease help me to solve this error.

    23. Hey Tim, do you have any idea how to make the dialogue box smaller? I’m using it on a Facebook tab and when it pops up it cuts off a bit of the box on the left side that wont fit in the 520 width. Any pointers would be appreciated :) John

    24. Can a facebook share button (like the one above) be put/embedded into the body of an email such that when a user clicks onto it, it will go to a popup like the example above and then a hosted  version of the email will be shared on the persons facebook page ??

      Know what i mean? someone out there must be doing this?? and has a solution.

    25. No. It requires <head> elements and JavaScript, neither of which can be in emails.

      • Thanks Tim much appreciated.

        I have made a little work around that isn’t that great but nevertheless works. I embed a ‘facebook share icon’ into the body of the email and hyperlink it to an html hosted version of that email.

        The user clicks on it, goes to that hosted version of the email (i.e. a web page) and then clicks on another ‘facebook share icon’ to share the “email”  on facebook.

        So there are two steps instead of one and its kind of amateurish and i probably won’t use it, but i learned alot in trying it.

        Thanks again! 

    26. Anonymous says:

      okay i have to update my post here.

      This CAN be done in one step. I have just received  a rather fancy email newsletter and when you click on their tiny Facebook icon (along with other shares)…..you get a popup (webpage) …..and you can share that email onto your facebook page…..in one step (i.e. using that popup to make a comment and then click share).

      Surely they are using web redirects etc but its all hidden to the user.

      All the best.

      • Sounds interesting, but I’d need to see it to see exactly what’s happening. If you resend the email example to tim at hyperarts dot com, I’ll try to provide insight into what they’re doing.

        But you can’t embed the Share button described in this post in an HTML email, afaik.

    27. Hi Tim, 
      I am currently using the following code but wasn’t able to pull the content and image within the forum thread. Any idea I can “extract” the content and image & share it to facebook? 

      share
       

    28. Yuvraj Singh says:

      can we use this “share box” on page load..whenever page loads it asks for share

    29. Tim – will this ‘share’ btn show up as a social interaction w/in google analytics? Or do I have to follow the more recent tutorial (http://www.hyperarts.com/blog/tracking-social-interactions-with-google-analytics/)? Ideally, our client wants to use a share btn so it posts to their feed. Thanks in advance – per usual!

      • We suspect that Facebook will eventually shut down the ability to create a Share button, particularly now that the Like button’s functionality has expanded. Of course, this means no custom image for the Share button.
        However, to answer your question, No, Google Analytics Social Tracking won’t track the custom Share Button. The shares would factor into Facebook Insights, but I don’t think you’d get clicks on the actual Share button.

    30. manish kakkar says:

      Hey Tim, I tried your example but I am getting error 191 when logged in through the different facebook ids I mean I can successfully post the article if I used the logins by which I created the Facebook application but getting error when use other loggins.
      Please help me … Thanks in advance!

    31. You may need to specify the “App on Facebook” URLs. Here’s more info on Error 191.

    32. Anonymous says:

      Hi Tim

      How could I get dynamic images for the image tag instead of specifying a complete image path.(og:image )

       

      • Hey Tim, I tried your example but I am getting error 191 when logged in through the different facebook ids I mean I can successfully post the article if I used the logins by which I created the Facebook application but getting error when use other loggi

    33. hey , can you tell me how we can use this idea in a loop .

    34. manish kakkar says:

      Hey Tim, I tried your example but I have few queries such as how can we break the line of description text?
      Is it possible to open the facebook page where the post display after posting or any message can be show to user?

    35. Is it possible to add a subdomain dynamically to the “link” attribute”

      For example: url = http://www.subdomain.maindomain.com

      $(‘#share_button1′).live(‘click’, function(e){ e.preventDefault(); FB.ui( { method: ‘feed’, name: ‘This will be a Promotion for North Bay’, link: ‘http://www.[add subdomain in here].maindomain.com’, picture: ‘http://www.maindomain.com/share-btn.jpg’, caption: ‘This is the content of the “caption” field.’, description: ‘This is the content of the “description” field, below the caption.’, }); });

    36. Mukesh Saini says:

      Type your comment here.We are using cakephp framework for our site and we used the above
      concept to share our site links at fb. But we are facing a problem, when
      we click on the facebook wall  shared link, the user got logged out from our current application. Can you please help us in this scenario.

    37. Hey thanks a lot for this! Works great for me.

      But it doesn’t work when I load the share button through an AJAX call. Can you please help me with this?

    38. I’m afraid I can’t help out there, Mukesh.

    39. Sorry. Can’t help there.

    40. Hi, It seems when I post content to my fb wall, from my website url.. it doesn’t close the generated window when the content has been posted. Any ideas?

    41.  I would like to resize the share button popup box to 500 px. How to do that ?
      Anybody who  know that help me, please . Many Thanks.

    42. I don’t think you can.

    43. Hey, I have a problem with that. It works with newest JQuery version but it doesn’t work with 1.3.2 Any idea why?

    44. Hi, first off all thank you very much for the help, cause it is very easy to follow. I have managed to successfully make the share button to work.
      I’d like to know if it is possible that after someone shares the content on his facebookm it will redirect to another page (ex: http://www.mywebsite.com/gift.html).
      Is this possible?

    45. I don’t think so, and it’d be terrible usability to redirect someone off of Facebook without informing them you were going to do that after they share you page.

      • basically I want to give a discount ticket to those who like my facebook page.
        So I made a share button on my website, then when they press the share button, it will pop out the dialog box as shown above. then I want  to redirect them to a page on my website where they can download the discount voucher.
        I have sine it on another website that’s why I was asking.

    46. thanks for this tutorial it was very helpful for me
      and can we count how many shares were done from that button????

    47. lastingrose says:

      Hello Tim,  I came to your very helpful tutorial after trying all solutions on the official developpers page 
      http://developers.facebook.com/docs/reference/dialogs/feed/ to implement it on  BLOGGER  at 
      http://lastingrose.blogspot.co.uk/

      However I keep getting the Error
      An error occurred with Sreedhar Pillai. Please try again later.API Error Code: 191API Error Description: The specified URL is not owned by the applicationError Message: redirect_uri is not owned by the application. 

      You have mentioned that the Link should be in same domain So Ihave  the following setting

      Link:http://lastingrose.blogspot.co.uk/2011/04/gramophonea-magical-radio-show-by-shalu.html (An inner page)
      App Domains: :http://lastingrose.blogspot.co.uk/

      I have also set a redirect page  and used it in the code as suggested elsewhere that a re direct _URI is required
      User Support URL: http://lastingrose.blogspot.co.uk/p/submit-your-guest-posts-or-comments.html

      Whatever I have done I still can’t get it working on BLOGGER. Do you know if there is any way? 
      Appreciate all help.

      P.S. For trial purpose I have borrowed your image link. which can be seen at the top right of the posts.

      Many thanks again

      Sreedhar Pillai

    48. Amit Kumar Pattnaik says:

      Thank you so much Tim for this share button. Though Facebook has now replaced the share button with LIKE button,  but I had always been looking for a share button. With a like button, a person can click the like button only once using his FB account. But say one who wanted to re-share that particular won’t find the LIKE button of any help! The share button is more likely to be used that time.
      And reading and following the steps in your tutorial, I could manage to add a working SHARE BUTTON on my page — (right at the bottom of the page) :  http://www.aamaodisha.org/download3.php

      But could you please help with some way to add a counter to this FB share button? i.e the no. of times that page has been shared.
      Thank you in advance.

    49. I really can’t advise re Blogger. My best advice would be to host your own blog, using WordPress, rather than using blogger. Sorry!

    50. You’d have to track clicks on the share button using Facebook Insights or, perhaps, Google Analytics (check “Referrers” to see if Facebook is sending traffic to that page).

    51. jkabhinandan says:

       Hi Tim,
      One more thing, how can we add multiple thumbnails as in the above examples it is shown a single image with every post on share.

    52. Is there anyway to choose to post to your fan page?  This one just posts to user Walls, a post to page option would be cool.

    53. thx tons! i wanna make a suggestion here that if you have jquery conflict, you can simply change the given jquery code provided by Tim here to
      $.noConflict();
      jQuery(document).ready(function(){jQuery(‘#share_button’).click(function(e){ … rest is the same

    54. how to share localhost:8080 server images to facebook .if you know idea plz share with me .thank you

    55. Is this still working today? I’ve followed the tutorial adding the code as above including my own fb app id. and there’s no action when i click the button.. Also the “Download our Facebook Share Button code” doesnt work. Please help :(

    56. mlmleadsgenerationblog says:

      Hi, thanks so much for this tutorial! You’re awesome :)

      Can you help me out? How do I make it so that the share button shares just post itself, not the whole website?

      Thanks,
      Roselle

    57. What do you mean by “facebook initializes my root site”? What is the URL of your tab?

    58. Ramanjit Singh says:

      I like it………workinggg

    59. Download link not works

    Trackbacks

    1. Web Design CA…

      Tutorial: How to Add a Facebook Share Button to your Own Website Pages | HyperArts…

    Speak Your Mind

    *