Keep social widgets in sync with pages loaded via history API
Keep Your Social CurrentAfter working with the HTML5 history API for the launch of You Rather, I hit a snag with keeping social widgets current. The content and URL would update, but the Like button would stick to the original document location. As it turns out, Twitter and Facebook widgets that canât simply be updated via typical jQuery selectors since they are parsed into iframes once the page loads. Fortunately for us, there is an easy fix.
In the function below, you can see that on push state we replace the HTML of the widgetâs parent with the new unparsed snippet. Then we search for a window level object of FB for Facebook and twttr for Twitter and reload each if they exist. For those looking to update Google Analytics youâll also notice there is a section where the URL is pushed as a new pageview. You earned those pageviews, so donât forget to claim them.
var update_social = function(title, url) { // Add a new pageview to Analytics if (typeof _gaq !== 'undefined') { window._gaq.push(['_trackPageview', url]); } //Need the full URL for outside sites var full_url = window.location.href; //Populate new Facebook widget $('#fb-like').html('<fb:like href="' + full_url + '" show_faces="false" width="350" action="like" send="true" font="segoe ui" colorscheme="light" />'); //Reload Facebook if (typeof FB !== 'undefined') { FB.XFBML.parse(document.getElementById('fb-like')); } //Populate new Twitter widget var twitter_text = title + " via " + "@buildinternet"; $('#twitter-share').html('<a href="https://twitter.com/share" vclass="twitter-share-button" data-url="' + full_url + '" data-text="'+ twitter_text +'" data-related="buildinternet">Tweet</a>'); //Reload Twitter if (typeof twttr !== 'undefined') { twttr.widgets.load(); } }For a look at this in action, take a look at the the demo page. The source code shows more of the context in a working History API driven page.
If youâre looking for more reading on how to get started with the history API, I recommend taking a look at this tutorial before looping back.
Powered By WizardRSS.com | Full Text RSS Feed | Amazon Plugin Wordpress | Android Forums | Wordpress Tutorials