How to Create a Twitter Button with Dynamic (custom) data-text message.

twitter

To add a  tweet button  , you obtain a twitter button code from the twitter resource page which consists of two parts – a html link tag and some javascript reference to the twitter widget.  You usually set your tweet button parameters such as twitter handle to follow, url to include, tweet content etc and the code which you include in your page is automatically generated.

<a class="twitter-share-button" id="twitterlink" href="https://twitter.com/share" data-size="large" data-via="denvycom">Tweet</a>
<script type="text/javascript">// <![CDATA[
!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>

Some times, you may want to create a tweet button with customized or more importantly dynamically generated tweet content. For example a web based game may need to include the score earned by the player in the tweet. 

A simple approach would be to write javascript code and modify the data-text attribute of the twitter button just before it gets clicked.  E.g ..

document.getElementById('twitterlink').setAttribute("data-text" , "I just achieved a " + "bingoo" + " on #2048Lagos a game where you find transport methods in lagos and score high." );

Unfortunately, this will not work. This is because the twitter script evaluates tag attributes on page load (and probably modifies the tag itself too) . From my experience the getElementById method returns a null value even when the correct id is provided.

A Dynamic Tweet Button

The solution is to dynamically generate a NEW twitter button in javascript , add it to your DOM model and reload the twitter script . In essence, for tweet buttons with dynamic attributes, you only add the twitter javascript code and create the twitter button on the fly using javascript .

An example is shown below

var link = document.createElement('a');
link.setAttribute('href', 'https://twitter.com/share');
link.setAttribute('class', 'twitter-share-button');
link.setAttribute('style', 'margin-top:5px;');
link.setAttribute("data-text" , "I just achieved a score of " + score + " on #2048Lagos a game where you find transport methods in lagos and score high." );
link.setAttribute("data-via" ,"denvycom") ;
link.setAttribute("data-size" ,"large") ;
this.lowermessageContainer.appendChild(link) ;
twttr.widgets.load();  //very important

Untitled-3

Note that after creating the twitter button (link) and setting all its attributes I do two important things. First I add it to the page DOM (this.lowermessageContainer.appendChild(link)) and I add call the twttr.widgets.load() method to re-evaluate the button.

Finally, if the button needs to be added on the page multiple times, remember to remove the previous button before adding the new updated version.


var elem = document.getElementById('twitterbox');
if (elem != null ){

elem.parentNode.removeChild(elem);
//document.getElementById("")
}

Finally, here is a JsFiddle Sample Code Snippet to demonstrate what we have learned above

Hope this is helpful.

About Vykthur

Mobile and Web App Developer and Researcher. Passionate about learning, teaching, and recently - writing.
This entry was posted in Developer Tips, Programming and tagged , , . Bookmark the permalink.
  • Igor

    Nice work, thanks.

    • Vykthur

      Thanks.

  • guest

    Hi there!

    I’m noob with Javascript and DOM manipulation, i can’t place to + score + the value that i want, instead i get [object HTMLDivElement].

    I have something like this:

    0 <– this is the value that i want to pass to tweet.

    I try to put an id="score" to the last class but it didn't work…

    Thanks for your time!

    • Vykthur

      Hi ,

      Two things ….
      Please ensure you are calling your javscript after the HTML content has been loaded. E.g you put it before the closing body tag … or use a library like jQuery to ensure the page has been loaded before you write your code.

      Second, to get the value of score in your snippet you should do somehting like this

      var score = document.getElementById(‘score’) ;

      To test and ensure this value is being captured properly, you can use an alert box to test its content

      alert(score) .

      You can find more related information on this stackoverflow link.

      http://stackoverflow.com/questions/8647216/get-content-of-a-div-using-javascript

      Let me know if this helps and goodluck with your javascript journey!

      -V.

      • guest

        You are awesome!!

        Your answer helped me a lot, and you answered my question immediately?

        Who are you the Superman?! 🙂

        I have spent so many hours the last 2 days trying to figure out how to make it work…

        Thanks again for everything!!

        • Vykthur

          Thanks for the kind words,
          I’m glad I was able to help!
          Again, best wishes with your javascript journeys!

  • hot40

    Hi, this article actually helped me quite a lot with figuring a few things out.. however like “guest” here I am also having a few issues on the output of the coding. I changed around the code a little and tried to use the method that you mentioned ” + value + ” however whatever I have tried seems to keep bringing up a [object HTMLDivElement] instead of the value. If you see the code in the following link could you maybe share some insight?

    http://jsfiddle.net/Gy3Z9/9/

    Thanks in advance.

    • Vykthur

      Hi,

      You have done the right thing! There just one little bug. When you try to get the value of DIV1, you need to specify that you need its value or innerHTML content.

      var MyDiv1 = document.getElementById(‘DIV1’).innerHTML;

      This should make it work.

      Iv written a fairly more intersting fiddle In which you can change the text on the fly and see what happens …

      http://jsfiddle.net/LEBz8/

      Glad the article helped you.

      Victor.

      • hot40

        Hey Victor , yes I figured it out almost after I clicked the send button. I came up with this:
        http://jsfiddle.net/rjdrundle/kS5KN/5/

        I checked out your fiddle but it doesn’t seem to “run” something… Am I missing something?
        What I am trying to accomplish is to grab the content of a div which is filled with data from another script, and take that and publish what appears in that div at the time the user presses the share/tweet button. However the + value + field also comes up blank when I apply the code from the fiddle I linked above. Maybe I should look for a different way of writing this up?

        Robbie

        • Vykthur

          Hi Robbie,

          I apologise. I dont use fiddle alot, so I didnt realize the link to the fiddle changes each time its updating.

          http://jsfiddle.net/LEBz8/1/

          This should work whenever you change anything

          • hot40

            Nice one 🙂 It would be cool if the Dynamic button would be the twitter share button as an idea. If you want I can show you the way I finally managed to do it. Any advice about attaching an image from a dynamic div as well together with the tweet?

  • Love what you have done here.

    I’m looking to do something similar in that I wish to have a drop down list populated with 10 different Twitter usernames. I want to be able to select a username and then have that user dynamically inserted into the “Tweet” as a mention.

    Is this possible? How would that look?

    Thanks in advance.

    • Vykthur

      Basically, all you have to do is to adjust the msg variable
      1.) Create your dropdown
      2.) Modify your msg variable to create a message that contains the selected value on your dropdown.

      var usernames = document.getElementById(“unamedropdown”);
      var strUser = usernames .options[usernames .selectedIndex].value;
      msg = “Hey this is a dynamic tweet with @” + strUser ;

      3.) Tweet.

      For more about getting the value in a dropdown … please see here
      http://stackoverflow.com/questions/1085801/get-selected-value-of-dropdownlist-using-javascript

      -V.

  • Lev Izraelit

    Thank you!

  • Andrew Sharrock

    I know this is rather old now but your JsFiddle does not delete the old tweet button. Is there a reason for this? I have been trying to fiddle around with it for an hour or so now and cant get it to work.

    • electrobento

      I’m having the same problem as well.

    • Jacqueline Wilson

      It worked when I changed the if (elem !=null) statement to parent div using jquery:

      //if div that holds twitter button is occupied, clear it out
      if ( $(‘#twdiv’).children().length > 0 ) {
      $(‘#twdiv’).empty();
      }

      • Victor Hall

        This code does not seem to work. Can you post your code or provide a link please? I really need help.

  • Victoria ‘Eddie’ Etim

    This post has been super helpful Vykthur. Please how can I implement something like this for facebook?

  • Victor Hall

    Hi @vykthur:disqus, the jsfiddle link you provided does not clear or get rid of the old button. It only as a new one. How will I be able to get rid of the previous button before the new one is added?
    var elem = document.getElementById(‘twtbox’);
    if (elem != null) {
    elem.parentNode.removeChild(elem);
    }

    this code gets rid of the button all together