Dynamically change Tweet Button "data-text" contents

I struggled with this for a couple of hours this morning, but finally got it working! The problem is essentially that you can only include the twitter widgets.js script once in the page, and that script evaluates the data-text attribute on load. Therefore, in your example, you dynamically set the data-text attribute before loading the script, which will work as expected. However, you can then make no further updates as the script has already run.

I saw this article suggesting you can call twttr.widgets.load() again at runtime to re-evaluate and re-render the buttons, however that didn't work for me. This is because that function re-evaluates <a> tags, not <iframe> tags!

So the solution, as pointed out here, is to completely remove the rendered <iframe> from the DOM, then make a new <a> element with all the appropriate attributes before calling twttr.widgets.load() to finally re-evaluate it and turn it into an <iframe>.

Please see this fiddle for a working example!


You can also use Twitter's createShareButton API call:

function callAsRequired(){
  var nodeID = 'YourTwitterNodeID'
  
  //Remove existing share button, if it exists.
  var myNode = document.getElementById(nodeID);
  while (myNode.firstChild) {
    myNode.removeChild(myNode.firstChild);
  }

  //Create button and customise
  twttr.widgets.createShareButton(
    'http://your.custom.url.here/',
    document.getElementById(nodeID),
    {
      count: 'none',
      text: 'Your custom tweet here'
    });
}