Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AddThis controls in an UpdatePanel - ensuring they are rendered correctly after async postback

Firstly may I apologise in advance for the quality of my post, as this is the first time I've posted on here. I've found some really useful answers on this site in the past and so having found myself in a position to give back I thought I'd give it a go.

After banging my head against a wall for some time, and finding very little solid information online, I finally found an answer to this problem that worked for me and answered a few questions so I thought I'd share my findings.

Scenario:

  • .Net user control that renders an addthis toolbox with uniquely specified url and title attributes.
  • An UpdatePanel that contains a repeater that displays multiple rows each of which contains an instance of the toolbox user control.
  • A "Show more results" button that refreshes the UpdatePanel, each time showing more results.

Problem:

When the page is first displayed everything is fine. All toolboxes display correctly and work as expected. However when the button is pressed and the UpdatePanel refreshes, the toolboxes disappear.

Solution:

Firstly I quickly ascertained from other people's questions and answers that I need to add an EndRequestHandler to my page using PageRequestManager that would handle the async postback request and trigger some javascript to render my toolboxes.

Next I needed to work out what this javascript should be.

I found a number of proposed solutions for this issue online, most using window.addthis=null and using jquery getScript() to re-run the addthis javascript however none of these solved the problem. I kept going back to the documentation on the AddThis site which stated that you should just use addthis.toolbox() to render your toolboxes with javascript, something that didn't seem to be working for me.

Then I had a lightbulb moment. It appeared that the addthis.toolbox() function was ignoring the addthis:url and addthis:title attributes I was setting in my toolbox divs and I realised that I needed to pass these attributes into addthis.toolbox() by defining them in the share config object. From then on things got much easier.

The final solution comes in 3 parts.

First is the tollbox DIV defined in the user control which has a unique ID and contains the addthis:url and addthis:title attributes:

<div id="toolBoxWrapper" class="toolBoxWrapper" runat="server">
    <div id='<%="toolBox_" + ControlId%>' class="addthis_toolbox"  addthis:url='<%=AssociatedUrl%>' addthis:title='<%=AssociatedName%>' >
        <a class="addthis_button_email"></a>
        <a class="addthis_button_facebook"></a>
        <a class="addthis_button_twitter"></a>
        <a class="addthis_button_print"></a>
        <a class="addthis_button_compact"></a>
        <a class="addthis_counter addthis_bubble_style"></a>
    </div>
</div>

Next I created a PreRender handler in the control to create the javascript that contains the definition of the control-specific addthis share config object. This can not be just contained in the ascx page as it doesn't work. It must be created using RegisterStartupScript in the server code:

    protected void Page_PreRender(object sender, EventArgs e)
    {
        // This code creates a control specific addthis_share config object so that
        // the toolbox can be re-created after an ajax async postback using addthis.toolbox()
        // which requires the url and title parameters to be included in the share config.
        StringBuilder sb = new StringBuilder();

        sb.AppendLine("var addthis_shareconfig_toolBox_" + ControlId + " = {");
        sb.AppendLine("url:\"" + AssociatedUrl + "\",");
        sb.AppendLine("title:\"" + AssociatedName + "\",");
        sb.AppendLine("passthrough: {");
        sb.AppendLine("   twitter: {");
        sb.AppendLine("       via: 'mydomain'");
        sb.AppendLine("   }");
        sb.AppendLine("}");
        sb.AppendLine("}");
        sb.AppendLine("if (toolBoxShareConfigs == null) var toolBoxShareConfigs = {};");
        sb.AppendLine("toolBoxShareConfigs['toolBox_" + ControlId + "'] = addthis_shareconfig_toolBox_" + ControlId + ";");

        ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "shareToolBox_" + ControlId, sb.ToString(), true);
    }

Finally I created an EndRequestHandler in my page using Sys.WebForms.PageRequestManager to be triggered once the UpdatePanel has refreshed. This goes through all the toolbox divs and finds the related share config object (reverting to a default if not found) and then calls addthis.toolbox() passing in the share config object:

<script type="text/javascript" language="javascript">
                Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
                function EndRequestHandler(sender, args) {
                    addthis_config.pubid = 'mypubid';
                    $(".addthis_toolbox").each(function () {
                        try
                        {
                            var shareConfig = toolBoxShareConfigs[this.id];
                        }
                        catch(err)
                        {
                            var shareConfig = {
                                passthrough: {
                                    twitter: {
                                        via: "mydomain"
                                    }
                                }
                            };
                        }
                        addthis.toolbox(this, addthis_config, shareConfig);
                    });
                }
            </script>

And that's it. Now my UpdatePanel works perfectly and all my addthis share toolboxes work correctly and have the right urls and titles.

There is one outstanding issue that I'm working on which is that the counter doesn't seem to show correctly after an async postback, however it's not an issue for me as I'm only using the UpdatePanel for mobile devices and am not displaying the counter. But if anyone has any ideas regarding this issue I'd love to hear from you.

like image 285
AndyW1206 Avatar asked Nov 02 '22 21:11

AndyW1206


1 Answers

I have been struggling also to find the most stable code for the AddThis Tool box. I found the following code as the simplest one. It works perfectly and all counters work correctly and the toolboxes is never disappear on panel refresh.

Here is the screen shot:

AddThis All Counters Available

JsFiddle: http://jsfiddle.net/hyip/oq3d6cpv/

Here is the Html code with all counters available:

<div class="addthis_toolbox addthis_default_style addthis_16x16_style" style="display:table; margin:0 auto;">     
     <a class="addthis_counter_facebook"></a>     
     <a class="addthis_counter_twitter"></a>     
     <a class="addthis_button_google_plusone"></a>     
     <a class="addthis_counter_linkedin"></a>     
     <a class="addthis_counter_pinterest_share"></a>     
     <a class="addthis_button_stumbleupon_badge"></a>     
     <a class="addthis_counter_delicious"></a>     
     <a class="addthis_counter_reddit"></a>     
     <a class="addthis_counter_vk"></a>     
     <a class="addthis_counter_odnoklassniki_ru"></a>     
     <a class="addthis_button_expanded at300m"></a>     
     <a class="addthis_counter addthis_bubble_style"></a>     
</div>

And here is the script in the js file:

(function(id, as, src) {
    if (document.getElementById(id)) return;
    var hjs = document.getElementsByTagName('head')[0], js = document.createElement('script'); 
    js.id = id; js.type = 'text/javascript'; js.async = as; js.src = src; hjs.appendChild(js);
}('aaddthis-wjs', 1, 'http://s7.addthis.com/js/300/addthis_widget.js#pubid=ra-your-addthis-id'));

In order that the ToolBox works with the correct URL, image, titles and description then we need to setup an Open Graph and Authorship in the Head of HTML.

Here is the minimum code to be placed in HTML Head:

<!-- Open Graph -->
<meta property="fb:admins" content="your-facebook-admin-id" />
<meta property="og:url" content="your-url-to-share" />
<meta property="og:image" content="path-to-your-default-image-to-share" />
<meta property="og:title" content="your-title-to-share" />
<meta property="og:description" content="your-description-to-share" />

<!-- Authorship --> 
<link rel="canonical" href="your-canonical-url" />
<link rel="image_src" href="your-default-image-to-share"/>
<link rel="icon" type="image/x-icon" href="/favicon.ico" />
<link rel="publisher" href="url-to-your-google-plus-with-page-id" />
<link rel="author" href="url-to-your-google-plus-with-profile-id" />

Hope this will be a sharing contribution to your solution.

UPDATE

If you need to show only Original Sharing Buttons (Fb, Tw, Ln, G+, Pin, Su) then AddThis has given us now with the counter for free.

Step 1: Add the following code to the of your website.

<script type="text/javascript" src="//s7.addthis.com/js/300/addthis_widget.js#pubid=ra-55dc7c7d2cb90e21" async="async"></script>

Step 2: Paste this code into whichever page you would like this tool to show up.

<div class="addthis_native_toolbox"></div>

Go to http://www.addthis.com/dashboard to customize your tools.

To put it on center use style="position: fixed; left: 50%; transform: translate(-50%);"
You may check here to see the code on live action.

like image 199
Chetabahana Avatar answered Nov 11 '22 07:11

Chetabahana