The solution I went with uses the iframe Tweet Button, and basically you just need a bit of javascript to manipulate the URL that configures the iframe Tweet Button. I went with the iframe Tweet Button over the javascript Tweet Button because the javascript one manipulates the DOM and replaces your anchor tag with an iframe, etc. You could theoretically dynamically change the tweet text for the javascript Tweet Button but it would be a little brittle, being dependent on how the javascript Tweet Button renders itself.
Enough jibber jabber, on to the code! You start by adding an iframe Tweet Button to the page:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<iframe id="tweet-button" allowtransparency="true" frameborder="0" scrolling="no" | |
src="http://platform.twitter.com/widgets/tweet_button.html?via=marcus_christie&text=Replace%20Me&count=horizontal" | |
style="width:110px; height:20px;"></iframe> |
Then you need this function which updates the text parameter of the iframe Tweet Button's query string (which of course will cause the button to reload):
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function updateTweetButtonText(message) { | |
var tweetButton = document.getElementById('tweet-button'); | |
tweetButton.src = tweetButton.src.replace(/&text=[^&]+/, "&text=" + encodeURIComponent(message) ); | |
} |
You can try it out right here. Click on the Tweet Button below and preview the message, which should be "Replace Me":
Now click on the button below which will call
updateTweetButtonText('I just dynamically updated the text of a Tweet Button!');
and then click on the Tweet Button again to see that the preview tweet has been updated: