How to Post a Tweet using JavaScript

In this post we will post a tweet using JavaScript. Let us assume we have a button like following


On click event of this button we want to post a tweet. For that we need to navigate to user to URL


After status we can put text to be tweeted. So on click event we need to navigate to this URL and append text to be tweeted. Very first we need to check whether tweet length is less than 140 or not. If it is more than 140 then we will show error message to user.


txttoTweet is variable containing text to be tweeted. In Else part we can tweet by redirecting to said URL as following,


Full code is as following,

 <script src="">
 <script type="text/javascript">
 $(document).ready(function () {
 $('#btnTweet').click(function (e) {
 var textToTweet = "Hi I am tweeting from here";
 if (textToTweet.length > 140) {
 alert('Tweet should be less than 140 Chars');
 else {
 var twtLink = '' +encodeURIComponent(textToTweet);,'_blank');

 <style type="text/css">
 #btnTweet {
 width: 159px;
 height: 38px;
 <h1>tweet from debugmode</h1>
 <button id="btnTweet">Tweet</button>

Some of the important point worth discussing here is as following,

  • Text to Tweet must be inside encodeURIComponet . Else you will get error.
  • Check Text to Tweet is less than 140 characters.
  • If you want can open windows as dialog also.

On running above script you should be getting output as following,


On click of Tweet button in next tab or windows as of your browser setting you will be asked to log in to Twitter, if not already logged in


On successfully sign in you should be able to tweet.


In this way you can tweet using JavaScript. I hope this post was useful. Thanks for reading.

7 thoughts on “How to Post a Tweet using JavaScript

  1. Thanks for sharing! shall i know how can i login through my twitter app, where should i give APIKey for login and logout?? reply as soon as possible… here i want user login through my twitter app (i.e. which i created therefore get user detail like his name, id, email ) so where can i give APIKey.

  2. Dhananjay, thank you for keeping this straightforward – for those of us who are novices can follow this. I used the javascript part in my solutio.

  3. Perfect tutorial for what I wanted to do. I thought it was going to be more complicated. Thank you.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s