How To Create A Dynamic “Tweet This” Button With JavaScript

Yesterday I posted some code on how to create dynamic Tweet This buttons with PHP, today I’m going to share a short code snippet you can really drag and drop into your editor to create a “Tweet This” button on your website.

You just need to copy and paste this code and adjust the src attribute of the image to point to your button:

<script type="text/javascript">
var twtTitle  = document.title;
var twtUrl    = location.href;
var maxLength = 140 - (twtUrl.length + 1);
if (twtTitle.length > maxLength) {
twtTitle = twtTitle.substr(0, (maxLength - 3))+'...';
}
var twtLink = 'http://twitter.com/home?status='+encodeURIComponent(twtTitle + ' ' + twtUrl);
document.write('<a href="'+twtLink+'" target="_blank"'+'><img src="tweetthis.gif"  border="0" alt="Tweet This!" /'+'><'+'/a>');
</script>

tweetthis-15

Share and Enjoy:
  • DZone
  • del.icio.us
  • Digg
  • StumbleUpon
  • Mixx
  • TwitThis
  • Technorati
  • FriendFeed
  • Google Bookmarks
  • BlinkList
  • blogmarks
  • Furl
  • LinkArena
  • Live
  • MySpace
  • NewsVine
  • Ping.fm
  • Reddit
  • Simpy
  • Spurl
  • Identi.ca
  • LinkedIn
  • MisterWong
  • Slashdot
  • Sphinn
  • Yahoo! Bookmarks
  • Facebook
  • RSS
  • Turn this article into a PDF!
  • Print this article!

Tags: , ,

6 Responses to “How To Create A Dynamic “Tweet This” Button With JavaScript”

  1. Josh says:

    Thanks Sascha, using your php and JS snippets on http://toonsays.com. Saved me some work.

  2. David Travis says:

    This is a great resource, thanks for making it available. We’re using it on our articles pages so that they can be more easily tweeted.

    Do you have any plans to add a URL shortening service, like bit.ly or TinyURL, to the script?

  3. Georgia says:

    Hi! I tried copying this into my blog layout, but I keep getting an error message that reads:

    XML error message: The document type declaration for root element type “html” must end with ‘>’.

    I don’t know what the problem is. Can you help? Thanks much! ~Georgia

  4. admin says:

    Sorry, seems to be a problem of your blog or the way you added this to your blog. I can’t help because I’ve never used blogspot.com myself.

  5. admin says:

    Thanks. You can’t use a URL shortening service with JavaScript - only the PHP version would allow this though this is not currently planned.
    The problem is that you don’t want to access the shortening service on every page load so you’d need to generate the short URL one time and then store it in your local database to serve it to the end user on every page request.

  6. mFavourite says:

    A brilliant website tweet-this button. We are now using your javascript version and is spot on.
    We like the fact there is no need to use any third party server/web company; which means the tweet-this is direct and fast. We are this will help our online presence even more.

    Great job
    Manager
    mFavourite.co.uk

Leave a Reply