Saturday, July 09, 2011

How to dynamically change the Tweet Button's tweet text

Looked around on the internet for a way to dynamically change the tweet text of the Tweet Button, but didn't find a good solution. Most of what I found involved setting the text when the page is being rendered server side or client side. But what I need for FuelMyRoute.com is a way to dynamically update the tweet text based on the user's activity in the page after it has rendered. (Specifically, based on the route provided by the user, I want to update the tweet text to say something specific about how much the user has saved per gallon of gas.)

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:



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):



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: