Twitter data-text attribute is not set using jQuery


#1

I’m using the following button from Twitter to tweet something.

<a id="tweet" href="https://twitter.com/share" class="twitter-share-button" data-text="Husam" data-size="large" data-count="none">Tweet it!</a>

    <script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+'://platform.twitter.com/widgets.js';fjs.parentNode.insertBefore(js,fjs);}}(document, 'script', 'twitter-wjs');
    </script>

In my JS file, I’m trying to change data-text attribute using jQuery attr function, so that it tweets what I would like to tweet.

$("#tweet").attr("data-text","what I want to tweet");

It just doesn’t work as expected, I can’t change the data-text attribute. Any ideas?

You can see the code here: http://codepen.io/husamp/pen/YyKLze


#2

Twitter’s widgets-js loads with the page, scanning for Tweet button markup and setting up the button based on the parameters it finds. Altering the resulting element would only alter the instructions used to create a Tweet button in the next scan.

The text query parameter of the rendered Tweet button’s anchor href contains the text component of the Tweet. Alter the href, not data-text.


#3

Unfortunately we don’t have any kind of live data-binding for the button widgets, and I would discourage you from changing the URL of a rendered widget (the implementation could change, which would break your script.)

If you’re trying to dynamically create a button for different text, use the twttr.widgets.createShareButton function, which allow you to provide the text as an argument and render it into the page:

For example:

twttr.widgets.createShareButton(document.location.href, { text: "What I want to Tweet" });

#4