I initialize the tweet button at the beginning of my app, after user interaction the current window\'s location is updated using HTML5 pushState, but the twitter button is still
I figured this out. Here's how to make this work.
The general idea is:
class
of your
for the twitter share button to be something other than .twitter-share-button
. Also give the
a style="display:none;"
. (or
) with a unique id
.
- In your jQuery, when you want to set the data for the twitter share button you will:
- 'clone()
the hidden, mis-named,
` tag from step #1
- On this clone, set the
data-url
etc... attributes as you'd like
- Remove the
style
attribute from the clone (unhide it)
- Change the
class
of the clone to twitter-share-button
append()
this clone to your from step 2.
- Use
$.getScript()
to load and run Twitter's Javascript. This will convert your cloned
into an
with all the right goop.
Here's my HTML (in Jade):
a.twitter-share-button-template(style="display:none;", href='https://twitter.com/share=', data-lang='en',
data-url='http://urlthatwillbe_dynamically_replaced',
data-via='ckindel', data-text='Check this out!',
data-counturl='http://counturlthatwillbe_dynamically_replaced') Share with Twitter
#twitter-share-button-div
Then in your client-side .js:
// the twitter share button does not natively support being dynamically
// updated after the page loads. We want to give it a unique (social_id)
// link whenver this modal is shown. We engage in some jQuery fun here to
// clone a 'hidden' twitter share button and then force the Twitter
// Javascript to load.
// remove any previous clone
$('#twitter-share-button-div').empty()
// create a clone of the twitter share button template
var clone = $('.twitter-share-button-template').clone()
// fix up our clone
clone.removeAttr("style"); // unhide the clone
clone.attr("data-url", someDynamicUrl);
clone.attr("data-counturl", someDynamicCountUrl);
clone.attr("class", "twitter-share-button");
// copy cloned button into div that we can clear later
$('#twitter-share-button-div').append(clone);
// reload twitter scripts to force them to run, converting a to iframe
$.getScript("http://platform.twitter.com/widgets.js");
I got the main clues for this solution from here:
http://tumblr.christophercamps.com/post/4072517874/dynamic-tweet-button-text-using-jquery