Dynamic Tweet Button Text Using jQuery

I recently needed to make a tweet button that would dynamically change the text that was posted to twitter based on the date.

Here is the standard code for a tweet button:

<a href="http://twitter.com/share"
    class="twitter-share-button"
    data-text="This is what we want to change dynamically"
    data-count="none" data-via="chris_camps">Tweet</a>
<script type="text/javascript"
    src="http://platform.twitter.com/widgets.js"></script>

Now, if you were using php or some other server-side language, this would be trivial:

    data-text="<?php print $dynamic_tweet_text ?>"

My situation required a javascript-only solution though, because it was a static html project without a backend infrastructure.

My first instinct was to do a ninja swap on page load using jQuery:

<script>
$(document).ready(function(){
    $('a[data-text]').each(function(){
      $(this).attr('data-text', "This will not work");
    });
});
</script>

I suspected this would fail, and it did. The reason is that $(document).ready() will execute after all the <script> tags in the document, including twitter’s <script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script>. When twitter’s js file runs, it immediately replaces the <a> with an iframe, and then it’s too late to affect it with our jQuery.

I had to somehow run twitter’s js file after my code. Thanks to jQuery the solution was easy!

<script>
$(document).ready(function(){
    $('a[data-text]').each(function(){
      $(this).attr('data-text', "This works!");
    });
    $.getScript('http://platform.twitter.com/widgets.js');
});
</script>

<a href="http://twitter.com/share"
    class="twitter-share-button"
    data-text="This is what we want to change dynamically"
    data-count="none" data-via="chris_camps">Tweet</a>
<!-- moved to the js above <script type="text/javascript"
    src="http://platform.twitter.com/widgets.js"></script> -->